Error/Exception层次图

异常处理

异常处理语句

1
2
3
4
5
6
7
8
9
10
11
12
try
{
语句1 //存在潜在异常的代码
}
catch (异常类异常对象)
{
语句2 //捕获到异常并进行处理的代码
}
finally
{
语句3 //最后必须执行的代码,无论是否捕获到异常
}

举两个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CatchExceptionDemo {
private static int calculate(int i, int j) {
return i / j;
}
public static void main(String[] args) {
CatchExceptionDemo obj = new CatchExceptionDemo ();
try {
int result = obj.calculate(9, 0);
System.out.println(result);
} catch (ArithmeticException e) {
System.err.println("发生异常:" + e.getMessage());
e.printStackTrace();//打印堆栈信息
}
System.out.println("end");
}

异常也可以在calculate方法中处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class CatchExceptionDemo2 {
private static int calculate(int i, int j) {
int result = 0;
try {
result = i / j;
} catch (ArithmeticException e) {
System.err.println("发生异常:" + e.toString());
e.printStackTrace();
}
return result;
}

public static void main(String[] args) {
CatchExceptionDemo2 obj = new CatchExceptionDemo2();
int result = obj.calculate(9, 0);
System.out.println(result);
System.out.println("end");
}
}
  • 一段代码可能会生成多个异常
  • 当引发异常时,会按顺序来查看每个 catch 语句,并执行第一个类型与异常类型匹配的语句 (异常类继承关系)
  • 执行其中的一条 catch 语句之后,其他的 catch 语句将被忽略
  • 多重catch,通常将捕获基类异常的catch语句放在后面

抛出异常

throw

1
2
3
4
5
public void set(int year, int month, int day)
{
if (month<1 || month>12)
throw new Exception("月份错误");
}

throws

[修饰符] 返回值类型方法([参数列表]) [throws 异常类]

1
public static int parseInt(String s) throws NumberFormatException

方法里抛出异常的栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ThrowsinMethod {
private int month;
public void setMonth(int month) throws Exception {
if (month<1 || month>12)
throw new Exception("月份错误");
this.month = month;
}
public static void main(String[] args) {
ThrowsinMethod obj = new ThrowsinMethod();
try {
obj.setMonth(13);
} catch (Exception e) {
e.printStackTrace();
}
}
}

方法上抛出异常的栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ThrowsOnMethod {
public static void doSomething() throws ClassNotFoundException {
Class clz = null;
clz = Class.forName("RaiseError");
System.out.println("over");
}
public static void main(String[] args) {
try {
doSomething();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

如果doSomething不处理异常,而是简单抛出异常,则调用doSomething的main方法就要求处理异常。
如果main也不处理,只是抛出异常的话,就由JVM来处理异常。