0x00
本章的大致简介
0x01 什么是异常
异常体系结构
所有的异常都是Throwable的子类
错误和异常不同,错误更加致命
Error
不在我们的应用程序之内,是java虚拟机内的错误
错误是致命性的错误,是程序无法控制和处理的
Exception
非运行时异常
所以异常是一定要处理的
0x02 捕获和抛出异常
通过try,catch,finally来捕获
package exceptionStudy;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try 监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//捕获异常
System.out.println("程序出现异常,b不能为0");
}finally {//处理善后工作
System.out.println("finally");
}
}
}
finally可以不要,但是可以用finally来关闭资源
捕获多个异常
package exceptionStudy;
public class Demo01 {
public static void main(String[] args) {
//如果要捕获多个异常,从小到大写
try {//try 监控区域
new Demo01().a();//调用a方法
}catch (Error e){//catch里的参数:想要捕获的异常类型
System.out.println("程序出现异常,b不能为0");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}finally {//处理善后工作
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
生成代码块的快捷键
package exceptionStudy;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//快捷键:ctrl alt t
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
Throw关键字
在方法中主动抛出异常
package exceptionStudy;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
new Demo01().test(a,b);
}
//假设在方法中,处理不了这个异常,方法上抛出异常,抛到下一级
public void test(int a ,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();//一般在方法钟主动抛出异常
}
}
}
0x03 自定义异常
package exceptionStudy;
//继承异常类,自定义异常
public class MyException extends Exception{
//传递数字>10
private int detail;
public MyException(int a){
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
0x04 实际运用中的经验总结
至此javase过了一遍