异常
异常包括错误Error和异常Exception。
Error
虚拟机运行错误,如栈溢出。无法处理。
Exception
一般由于程序逻辑出错导致。可以处理。
异常处理
捕获异常
public class Demo01 {
public static void main(String[] args) {
int a = 1,b = 0;
//选中要捕获的代码,Ctrl + Alt + T,快捷键,快速生成try-catch
try {//捕获异常的代码
System.out.println(a/b);
}catch (ArithmeticException e){//可能出现的异常
System.out.println("除数无法为0");//异常出现时,不执行异常代码,执行这条代码
}catch (Throwable t){//异常类型由小到大
System.out.println("error");
}finally {//最终无论是否出现异常,都会执行的代码
System.out.println("end");
}
}
}
主动抛出异常
public class Demo02 {
public static void main(String[] args) {
int a = 1,b = 0;
try {
if (b == 0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
} catch (Exception e) {
System.exit(1);//程序结束
e.printStackTrace();
} finally {
}
}
}
抛出异常
public class Demo02 {
public static void main(String[] args) {
try {
new Demo02().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b) throws ArithmeticException{//抛出异常
if (b == 0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}
}
自定义异常
public class MyException extends Exception{//继承异常
private int detail;
public MyException(int a) {//构造器
detail = a;
}
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
public class Test {
public static void test(int a) throws MyException {
if (a>10){
throw new MyException(a);//主动抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException=>"+e);//打印异常信息,自定义里面的toString内容
}
}
}