文章目录
- 🥽 异常概述
- 🥽 异常的分类
- 🥽 异常的处理
- 🌊 异常处理机制一:try-catch-finally
- 💦 语法结构
- 💦 try-catch
- 💦 finally
- 💦 try-catch-finally处理异常的执行流程
- 🌊 编译时异常与运行时异常的不同处理
- 🌊 异常处理机制二:throws+异常类型
- 🌊 重写方法异常抛出的规则
- 🌊 异常处理方式的选择
- 🥽 手动抛出异常对象
- 🥽 用户自定义异常类
异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)
Java程序在执行过程中所发生的异常事件可分为两类:
对于这些错误,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。比如:除数为0,数组下标越界等。
异常的分类:编译时异常和运行时异常
Exception exception = new ClassCastException();
——创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样try{
...... //可能产生异常的代码
}
catch( ExceptionName1 e ){
...... //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
...... //当产生ExceptionName2型异常时的处置措施
}
......
[ finally{
...... //无论是否发生异常,都无条件执行的语句
} ]
@Testpublic void test1() {String str = "123";str = "abc";int num = 0;try {num = Integer.parseInt(str);System.out.println("hello-----1");} catch (NumberFormatException e) {//System.out.println("出现数值转换异常了,不要着急....");//String getMessage()://System.out.println(e.getMessage());//printStackTrace():e.printStackTrace();} catch (NullPointerException e) {System.out.println("出现空指针异常了,不要着急....");} catch (Exception e) {System.out.println("出现异常了,不要着急....");}System.out.println(num);System.out.println("hello-----2");}
使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
@Testpublic void testMethod() {int num = method();System.out.println(num);}public int method() {try {int[] arr = new int[10];System.out.println(arr[10]); // 出现异常,生成异常对象进入对应的catch语句return 1;} catch (ArrayIndexOutOfBoundsException e) {e.printStackTrace();return 2; // 由于有finally语句(一定会执行),所以进入finally语句再回来执行return} finally {System.out.println("我一定会被执行");return 3; // 由于在finally语句中进行了return,直接结束该方法返回3}}
@Testpublic void test2() {FileInputStream fis = null;try {File file = new File("hello1.txt");fis = new FileInputStream(file);int data = fis.read();while (data != -1) {System.out.print((char) data);data = fis.read();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 避免空指针异常// fis = new FileInputStream(file); 可能报异常而创建失败会使得fis为nullif (fis != null) fis.close();} catch (IOException e) {e.printStackTrace();}}}
如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。
“throws + 异常类型” 写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!
public static void main(String[] args) {// method2没有对method1抛出的异常进行处理// 而是继续抛出异常,所以此处需要异常处理try {method2();} catch (IOException e) {e.printStackTrace();}// 由于method3中对异常进行处理了,没有抛出异常// 此处不用异常处理// method3();}public static void method3() {try {method2();} catch (IOException e) {e.printStackTrace();}}public static void method2() throws IOException {method1();}public static void method1() throws FileNotFoundException, IOException {File file = new File("hello1.txt");FileInputStream fis = new FileInputStream(file);int data = fis.read();while (data != -1) {System.out.print((char) data);data = fis.read();}fis.close();// 由于文件不存在// File file = new File("hello1.txt"); 此处就会生成异常对象// File file = new File("hello1.txt"); 后的代码不会执行System.out.println("hahaha!");}
try-catch-finally:真正的将异常给处理掉了。 throws的方式只是将异常抛给了方法的调用者。并没有真正将异常处理掉。
子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型。
public class OverrideTest {public static void main(String[] args) {OverrideTest test = new OverrideTest();// 此时将子类作为形参传递给接收父类类型参数的方法// 如果子类重写方法抛出的异常小于等于父类被重写方法抛出的异常// 则在调用方法中可以对异常继续捕获处理// 如果子类重写方法抛出的异常大于父类被重写方法抛出的异常// 则在调用方法中不能对异常继续捕获处理,抛出的异常类型大于catch中捕获的异常test.display(new SubClass());}public void display(SuperClass s) {try {s.method();} catch (IOException e) {e.printStackTrace();}}
}class SuperClass {public void method() throws IOException {}
}class SubClass extends SuperClass {public void method() throws FileNotFoundException {}
}
public class StudentTest {public static void main(String[] args) {try {Student s = new Student();s.regist(-1001); // 如果在regist方法中出现逻辑不允许的异常// 手动生成一个异常对象,并将该异常对象抛出// 可以阻止后续代码的执行,阻止逻辑错误后继续运行System.out.println(s);} catch (Exception e) {
// e.printStackTrace();System.out.println(e.getMessage());}}
}class Student{private int id;// 抛出手动生成的异常对象public void regist(int id) throws Exception {if(id > 0){this.id = id;}else{//System.out.println("您输入的数据非法!");//手动抛出异常对象//throw new RuntimeException("您输入的数据非法!");//传入的字符串相当于为e.getMessage()读取的属性赋值throw new Exception("您输入的数据非法!");}}@Overridepublic String toString() {return "Student [id=" + id + "]";}
}
public class MyException extends Exception{// serialVersionUID,用于唯一标识一个类,序列化时用于不同类的识别static final long serialVersionUID = -7034897193246939L;public MyException(){}public MyException(String msg){super(msg); // 调用父类相应的构造器为e.getMessage()读取的属性赋值}
}
public class StudentTest {public static void main(String[] args) {try {Student s = new Student();s.regist(-1001);System.out.println(s);} catch (Exception e) {
// e.printStackTrace();System.out.println(e.getMessage());}}
}class Student{private int id;public void regist(int id) throws Exception {if(id > 0){this.id = id;}else{
// System.out.println("您输入的数据非法!");//手动抛出异常对象
// throw new RuntimeException("您输入的数据非法!");
// throw new Exception("您输入的数据非法!");// 抛出自定义异常对象// 手动抛出的只能是异常体系的对象throw new MyException("不能输入负数");}}@Overridepublic String toString() {return "Student [id=" + id + "]";}
}
下一篇:Web API的方法论及实践