引出
java异常机制初步
异常是什么
程序运行时,产生非正常的结果。


java异常体系




异常的体系:

异常是可抛出的

不同的异常处理:
- 如果一个异常类继承Exception,可检测异常:必须处理
- 继承RuntimeException,运行时异常,可以不处理, 实际工作中,使用继承RuntimeException

如果是Exception,则可以捕获所有异常:

try…catch…finally
最终的
try{
} catch(Exception e){
}finally{
有无异常一定会执行。
}

throws—方法
位置: 出现在方法上,告诉调用者,方法可能有异常。

throw—动词抛出
动词: 抛出异常对象。

public class ExceptionDemo {
public static void main(String[] args) {
try {
double c = divide(5, 0);
} catch (Exception e) {
// throw new RuntimeException(e);
System.out.println(e.getMessage());
System.out.println(e.hashCode());
System.out.println(e.getLocalizedMessage());
System.out.println(e.getClass());
}
}
public static double divide(int a,int b){
if(b==0) throw new RuntimeException("除数不能为0");
return 1.0*a/b;
}
}
自定义异常
继承RuntimeException
package com.woniuxy.exception;
/**
* 自定义异常
*/
public class CarException extends RuntimeException{ // 继承RuntimeException
public CarException(String msg){
super(msg); // 调用父类的构造方法
}
}
总结
1.java的异常体系;
2.try catch 的finally;
3.throws和throw;
4.自定义异常;



![[数据结构习题]链表——单链表重排](https://img-blog.csdnimg.cn/5e936a0dc79247a9b1ff7e8c3daefec8.gif#pic_center)











