- Java 编程示例
- 示例 - 首页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用资源
- Java - 快速指南
- Java - 有用资源
如何使用 catch 处理 Java 中的链式异常
问题描述
如何使用 catch 处理链式异常?
解决方案
此示例展示如何使用多个 catch 块处理链式异常。
public class Main{
public static void main (String args[])throws Exception {
int n = 20, result = 0;
try {
result = n/0;
System.out.println("The result is "+result);
} catch(ArithmeticException ex) {
System.out.println ("Arithmetic exception occoured: "+ex);
try {
throw new NumberFormatException();
} catch(NumberFormatException ex1) {
System.out.println ("Chained exception thrown manually : "+ex1);
}
}
}
}
结果
上述代码示例将产生以下结果。
Arithmetic exception occoured : java.lang.ArithmeticException: / by zero Chained exception thrown manually : java.lang.NumberFormatException
以下是在 Java 中使用 catch 处理链式异常的另一个示例
public class Main{
public static void main (String args[])throws Exception {
int n = 20,result = 0;
try{
result = n/0;
System.out.println("The result is"+result);
}catch(ArithmeticException ex){
System.out.println("Arithmetic exception occoured: "+ex);
try{
int data = 50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
}
上述代码示例将产生以下结果。
Arithmetic exception occoured: java.lang.ArithmeticException: / by zero java.lang.ArithmeticException: / by zero rest of the code...
java_exceptions.htm
广告