练习一
public class RuntimeExceptionDemo {
static void method1(){
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
} finally{
System.out.println("用A方法的finally");
}
}
static void method2(){
try {
System.out.println("进入方法b");
return;
} finally {
System.out.println("用B方法的finally");
}
}
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
method2();
}
}
结果:
重点:
当程序执行try块,catch块时遇到return语句或者throw语句,这两个语句都会导致该方法立即结束,所以系统并不会立即执行这两个语句,而是去寻找该异常处理流程中的finally块,如果没有finally块,程序立即执行return语句或者throw语句,方法终止。如果有finally块,系统立即开始执行finally块,只有当finally块执行完成后,系统才会再次跳回来执行try块、catch块里的 return或throw语句,如果finally块里也使用了return或throw等导致方法终止的语句,则finally块已经终止了方法,不用 再跳回去执行try块、catch块里的任何代码了。
综上:尽量避免在finally块里使用return或throw等导致方法终止的语句,否则可能出现一些很奇怪的情况!
练习二
package exercise;
/**
* * 编写应用程序EcmDef.java,接收命令行的两个参数,
* 要求不能输入负数,计算两数相除。
* 对 数 据 类 型 不 一 致(NumberFormatException)、
* 缺 少 命 令 行 参 数(ArrayIndexOutOfBoundsException、
* 除0(ArithmeticException)及输入负数(EcDef自定义的异常)进行异常处理。
*
* 提示:
* (1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
* (2)在main()方法中使用异常处理语句进行异常处理。
* (3)在程序中,自定义对应输入负数的异常类(EcDef)。
* (4)运行时接受参数java EcmDef2010//args[0]=“20”args[1]=“10”
* (5)Interger类的static方法parseInt(Strings)将s转换成对应的int值。
* 如:int a=Interger.parseInt(“314”);//a=314;
*/
public class Ecmdef {
public static void main(String[] args) {
try{
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = ecm(i,j);
System.out.println(result);
}catch(NumberFormatException e){
System.out.println("数据类型不一致");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("缺少命令行参数");
}catch(ArithmeticException e){
System.out.println("除0");
}catch(EcDef e){
System.out.println(e.getMessage());
}
}
public static int ecm(int i , int j) throws EcDef{
if(i<0 || j<0){
throw new EcDef("两数中有一个为负数");
}
return i/j ;
}
}
package exercise;
//自定义异常类
public class EcDef extends Exception {
static final long serialVersionUID = -33893124229948L;
public EcDef(){
}
public EcDef(String string) {
super(string);
}
}
Java异常处理总结
异常的体系结构