异常
中断了正常指令流的事件;
示例代码
int i = 1/0;
System.out.println(i);
错误日志
Exception in thread "main" java.lang.ArithmeticException: / by zero
at kkb_006_factoryMethodPattern.Test.main(Test.java:22)
注意
- 语法上是正确的,编译能通过,发生在运行过程中。
- 异常发生后,发生地后面的代码不会再执行
执行过程中发生异常时,虚拟机会生成一个异常对象。
异常对象
Throwable
|- exception
|-RuntimeException(uncheck exception)
|-IOException(check exception)
|- error
上方示例错误日志中ArithmeticException
是RuntimeException
的子类
try catch
System.out.println(1);
try {
int i = 1/0;
System.out.println(1.5);
} catch (Exception e) { //发生异常则执行
// TODO: handle exception
System.out.println(2);
e.printStackTrace();
}finally {
System.out.println(3); //一定执行
}
System.out.println(4);
结果
1
2
java.lang.ArithmeticException: / by zero
at kkb_006_factoryMethodPattern.Test.main(Test.java:24)
3
4
主动抛异常
public class User {
private int age;
public void setAge(int age) {
if (age < 0) {
RuntimeException exception = new RuntimeException();
throw exception; //throw, 抛出异常
}
this.age = age;
}
public User() {
// TODO Auto-generated constructor stub
}
}
不可使用 Exception exception = new Exception();
,否则编译无法通过,报错信息 如下图。
Unresolved compilation problem:
Unhandled exception type Exception
因为,Exception属于check exception,编译阶段检查到这样的exception,会无法通过。错误提示如下图
错误提示.png
提示需要这样处理
-
Add throws declaration (添加异常/抛出声明)
注意区分:throws, 是用来声明异常。而throw是用来抛出异常。
在函数内处理,声明异常 代码public void setAge(int age) throws Exception{ if (age < 0) { Exception exception = new Exception(); throw exception; } this.age = age; }
-
Surround with try/catch (使用try/catch包围)
在函数被调用的地方处理 ,使用try/catch 代码User user = new User(); try { user.setAge(-22); } catch (Exception e) { // TODO: handle exception }
异常处理,是java开发中比较体现功力的地方,需要根据经验去判断 是否需要处理、使用上面哪一种处理
网友评论