和异常有联系的关键字:try catch、finally、throw(主动抛出异常)、throws(类上抛出异常)
快捷键(Ctrl+alt+t)可以直接生成try catch、finally代码块
try关键字后面跟的是可能出现异常的语句
catch后面打印异常信息
无论有没有异常出现总会执行finally语句,finally语句一般关闭资源(IO流等)的作用
异常处理代码
package com.YiChang.demo01;
public class Yichang {
public static void main(String[] args) {
int a=10;
int b=0;
//ctrl + alt +t直接生成代码块
try {
System.out.println(a/b);
}catch (Exception e){
System.out.println("出现异常");
}finally {
System.out.println("finally");
}
}
}
自定义异常(MyException)
package com.YiChang.demo01;
public class MyException extends Exception{
private int detail;
public MyException(int detail) {
this.detail = detail;
}
@Override
public String toString() {
return "MyException{" + detail + '}';
}
}
测试自定义异常
package com.YiChang.demo01;
public class Test {
static void test(int a) throws MyException {
if(a>10){
throw new MyException(a);
}
else System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException==>"+e);
}
}
}