Java异常类型及处理详情

网友投稿 293 2022-12-05

Java异常类型及处理详情

目录一、异常处理的关键字1、throw2、throws

异常结构为:

Throwable 为顶级父类

子类Error为严重报错 ,

子类Exception就是我们所说的异常了

一、异常处理的关键字

java中处理异常的有五个关键字: try、catch 、finally 、 throw 、throws

throw抛出异常 , thorws声明异常 , 捕获异常 try_catch

1、throw

public class SegmentFault {

public static void main(String[] argsOdxlwzSLg) {

/**

* 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

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 (!OdxlwzSLgpath.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: 文件不存在

不管程序怎样,这里都会被执行

注意事项 :try、 catch、 finally、都不可以单独使用

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解mybatis generator代码生成器的使用
下一篇:Maven中plugins与pluginManagement的区别说明
相关文章

 发表评论

暂时没有评论,来抢沙发吧~