Java 异常主要依赖于 Try, catch, finally, throw, throws
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a/b;
System.out.println("The result is: " + c);
}
catch (IndexOutOfBoundsException ie)
{
System.out.println("The Array is out of index");
}
catch (NumberFormatException ne)
{
System.out.println(ne.toString());
}
catch (ArithmeticException ae)
{
System.out.println(ae.toString());
}
catch (Exception e)
{
System.out.println("Unknown exception: " + e.toString());
}
NullPointerException //空异常
先捕获小异常, 在捕获大异常 (先子类异常, 在父类异常, 所有 exception在最后, 异常只执行一次)
可以一次捕捉多种类型异常:
- 用 | 分割
- 捕获多种类型异常时, 异常变量有 隐式的 final所以不能再赋值
catch (IndexOutOfBoundsException | NumberFormatException e)
{
System.out.println("The Array is out of index");
}
Finally 回收资源, 不要在 finally 语句里面有 return 或 throw 语句
自动关闭资源的 try 语句, 在try 后面 加 (), 括号里面声明初始化 资源
try
(
BufferedReader br = new BufferedReader(new FileReader("BaseLibrary.java")); //执行完后自动关闭
)
{
System.out.println(br.readLine());
}
10.3 Checked 和 runtime 异常
Throws exception -- Checked 异常 在 方法声明后面, 在编译时提示有无异常
使用 throw 抛出异常, 调用它的方法处理异常
10.4 自定义异常