import java.io.FileInputStream;
import java.io.IOException;
public class ExceptionTest {
public static void main(String[] args) {
try{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a/b;
System.out.println("c的值为:" + c);
}
catch(IndexOutOfBoundsException ie)
{
System.out.println("数组的下标越界,请检查下标");
}
catch(NumberFormatException g)
{
System.out.println("数字的格式的错误,程序只能接受整数的参数");
}
catch(ArithmeticException d)
{
System.out.println("算数异常");
}
catch(NullPointerException c)
{
System.out.println("空指针异常");
}
catch(Exception a)
{
System.out.println("未知异常");
}
//可以一次捕获多个异常
// catch(IndexOutOfBoundsException|NumberFormatException|ArithmeticException ss)
{
System.out.println("在Java7中新增加的,可以一次捕获多个异常");
}
try{
FileInputStream fil = new FileInputStream("guoguo.txt");
}
catch(IOException o)
{
System.out.println(o.getMessage()); //guoguo.txt (No such file or directory)
o.printStackTrace();
/*
异常跟踪栈信息:
java.io.FileNotFoundException: guoguo.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at ExceptionTest.main(ExceptionTest.java:42)
* */
}
}
}
/*
* (1)异常检查机制:编译器通过try来捕获一个异常,通过与catch后面的异常的类型进行对比,如果找到像匹配的异常,则执行相对应的
* catch的方法体中的代码,给出提示。
* (2)在catch中的异常的出现的先后的顺序应该是子类的异常排在父类的异常的前面,负责子类的异常永远也不会得到执行。(先处理小异常,在处理大异常)
* (3)实际在程序运行中,无论在代码中是否有try来捕获异常,如果在运行过程中发生了异常,系统总会生成一个异常,如果没有try类捕获则
* 程序会自动终止,并且报错。
* (4)在Java7中新增加的,可以一次捕获多个异常,捕获的异常变量使用了隐式的final来修饰,因此不能再对异常变量在重新赋值。
* */
Java的异常检查机制
最新推荐文章于 2022-01-27 11:37:21 发布