1.异常关键字
2.异常分类
异常关键字
- try
- catch
- finally
- throw
- throws
🌟在什么情况下,try-catch后面的代码不执行?
1.throw抛出
2.catch中没有正常的进行异常
3.在try中遇到return
🌟怎么样才可以将try-catch后面的代码,必须执行?
只要将必须执行的代码放入finally中,那么这个代码一定执行(先执行finally再执行return)
🌟什么代码会放在finally中
关闭数据库 关闭IO流资源 关闭socket资源
🌟让finally中代码不执行```
System.exit(0);
🌟在JDK1.7后,异常新处理方式:可以并列用|
catch (IllegalArgumentException|NullPointerException e){...}
🌟throw和throws区别
1.位置不同 throw定义在方法内,throws定义在方法的签名处
2.内容不同 throw+异常对象(检测异常,运行时异常)throws可以多个类型用,拼接
3.作用不同
throw异常出现的源头,制造异常,(catch后的异常多个异常用|)
throws在方法声明处,告诉方法调用者,这个方法可能会出现的这些异常,然后调用者对这个异常处理
🌟子类中的异常要小于父类
try {
//可能会发生的异常
Scanner sc=new Scanner(System.in);
System.out.println("num1=");
int num1=sc.nextInt();
System.out.println("num2=");
int num2=sc.nextInt();
//System.exit(0);//终止代码
//return;//catch里对语句都不执行
}catch (IllegalArgumentException|NullPointerException e){
//1
System.out.println("problem");
//2打印异常信息
//2.1调用toString方法,显示异常的类名,
System.out.println(e);
System.out.println(e.toString());
//2.2显示异常描述信息的字符串,如果没有就显示null
System.out.println(e.getMessage());
//2.3显示堆栈异常信息 打印异常完整信息
e.printStackTrace();
//3.抛出异常 后面的内容不执行
throw e;
}
例子
public class j1 {
public static void main(String[] args) throws Exception{//抛给虚拟机
devide();
}
private static void devide()throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("num1=");
int num1 = sc.nextInt();
System.out.println("num2=");
int num2 = sc.nextInt();
if(num2==0){
try{
throw new Exception();
}catch (Exception e){
System.out.println(e.toString());//java.lang.Exception
System.out.println(e);//java.lang.Exception
System.out.println(e.getMessage());//null打印异常信息
/*
java.lang.Exception
at j1.devide(j1.java:40)
at j1.main(j1.java:5)
*/
e.printStackTrace();
throw e;
}
}
}
}
异常分类
自定义异常:如果是运行时异常(比如访问某数据,结果那个数据是空指针),在使用时无需额外处理,如果是检查异常(比如某包名路径),那么使用时需要try-catch捕获或者throws向上抛