异常结构为:
Throwable 为顶级父类
子类 Error 为严重报错 , 子类 Exception 就是我们所说的异常了
一、异常处理的关键字
java 中处理异常的有五个关键字: try 、 catch 、 finally 、 throw 、 throws
throw 抛出异常 , thorws 声明异常 , 捕获异常 try_catch
1、throw
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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: 数组下标越界异常
2、throws
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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(): 获取异常类型及描述信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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: 文件不存在
不管程序怎样,这里都会被执行
注意事项 : try 、 catch 、 finally 、都不可以单独使用
到此这篇关于 Java 异常类型及处理详情的文章就介绍到这了,更多相关 Java 异常类型及处理内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://segmentfault测试数据/a/1190000040525473