Java异常类型及处理方法是怎样的,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
异常结构为:
Throwable
为顶级父类
子类Error
为严重报错 ,
子类Exception
就是我们所说的异常了
java
中处理异常的有五个关键字: try
、catch
、finally
、 throw
、throws
throw
抛出异常 , thorws
声明异常 , 捕获异常 try_catch
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: 数组下标越界异常
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: 文件不存在
不管程序怎样,这里都会被执行
注意事项 :try
、 catch
、 finally
、都不可以单独使用
关于Java异常类型及处理方法是怎样的问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。