Java异常类型及使用
source link: https://segmentfault.com/a/1190000040525473
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Java异常类型及处理
前言: 异常指的是程序在执行过程中,出现了非正常情况,导致了java
的jvm
停止停止。
异常结构为:
Throwable
为顶级父类
- 子类
Error
为严重报错 , - 子类
Exception
就是我们所说的异常了
异常处理的关键字
java
中处理异常的有五个关键字: try、catch 、finally 、 throw 、throws
throw
抛出异常 , thorws
声明异常 , 捕获异常 try_catch
throw
public class SegmentFault { public static void main(String[] args) { /** * throw 抛出异常 * 格式 - throw new 异常类名(参数); * */ // 创建一个数组 int [] arr = { 2, 4, 56 ,5}; // 根据索引找到对应的元素 int index = 4; int element = getElement(arr,index); System.out.println(element); System.out.println("owo"); // 运行错误 无法继续 } /** throw 抛出异常 提醒你必须处理 */ public static int getElement(int [] arr, int index){ // 判断数组索引是否越界 if (index < 0 || index > arr.length -1){ /** * 条件满足越界 当执行到throw抛出异常后就无法运行,结束方法并且提示 * */ throw new ArrayIndexOutOfBoundsException("数组下标越界异常"); } int element = arr[index]; return element; } }
异常结果为:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 数组下标越界异常
throws
public class SegmentFault{ public static void main(String [] args){ read("a.txt"); } public static void read(String path) throws FileNotFoundException, IOException { if (!path.equals("a.txt")){ // 如果没有a.txt // 如果不是 a.txt 该文件不存在 是一个错误 也就是异常 throw throw new FileNotFoundException("文件不存在"); } if (!path.equals("b.txt")){ throw new IOException("文件不存在"); } } }
异常结果为:
Exception in thread "main" java.io.IOException: 文件不存在
try、catch、finally + Throwable中的常用方法。
Throwable常用方法如下printStackTrace() :
*打印异常详细信息。getMessage() :
获取异常原因。toString():
获取异常类型及描述信息。
public class Demo03 { public static void main(String[] args) { /** * try- catch 捕获异常 * */ // 可能会生成的异常 try { // 捕获或者声明 read("b.txt"); } catch (FileNotFoundException e) { // 使用某种捕获,实现对异常的处理 System.out.println(e); /** * Throwable中的查看方法 * getMessage 获取异常信息 提示给用户看的 * toString 获取异常的类型和异常描述(不用) * printStackTrace * */ System.out.println("Throwable常用方法测试"); System.out.println(e.getMessage()); // 文件不存在 System.out.println(e.toString()); e.printStackTrace(); } finally { System.out.println("不管程序怎样,这里都会被执行"); } System.out.println("over"); } public static void read(String path) throws FileNotFoundException { if (!path.equals("a.txt")) { throw new FileNotFoundException("文件不存在"); } } }
输出结果为:
java.io.FileNotFoundException: 文件不存在
-----Throwable常用方法测试------
文件不存在
java.io.FileNotFoundException: 文件不存在
不管程序怎样,这里都会被执行
over
注意事项 :try catch finally都不可以单独使用
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK