1.Exception(异常)

  • 异常分为编译时异常和运行时异常
  • 对于编译异常,程序必须处理
  • 对于运行时异常,程序中如果没有处理,默认就是throws

1.1 try-catch

  • 基本语法
  1. try{
  2. //代码
  3. }catch (Exception e){
  4. //try代码发生异常catch执行
  5. //可以有多个catch分别捕获不同异常相应处理,子类异常在前,父类异常在后
  6. }finally {
  7. //不管try发不发生异常,finally中的代码都会执行
  8. //没有finally是允许的
  9. //可以try-finally,没有catch,发生异常程序会直接throw
  10. }
  • 没有try-catch默认throws
  • 一个实例:输入的如果不是整数就反复提醒输入
  1. package exception_;
  2. import java.util.Scanner;
  3. public class Exception01 {
  4. public static void main(String[] args) {
  5. int num = 0;
  6. Scanner scanner = new Scanner(System.in);
  7. String input = "";
  8. while (true){
  9. input = scanner.next();
  10. try {
  11. num = Integer.parseInt(input);
  12. break;
  13. } catch (NumberFormatException e) {
  14. System.out.println("你输入的不是整数");
  15. }
  16. }
  17. System.out.println("你输入的是" + num);
  18. }
  19. }

1.2 throws

  • 不对异常进行处理,而抛给调用者进行处理
    这里的FileNotFoundException是编译时异常,因为没有文件d://aa.txt,程序会报错,但是把异常抛出后程序不会报错,异常会抛给调用f1的函数处理。
  1. package exception_;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. public class Exception02 {
  5. void f1() throws FileNotFoundException{
  6. FileInputStream file = new FileInputStream("d://aa.txt");
  7. }
  8. }
  • 子类重写父类的方法时,子类方法抛出的异常必须和父类方法异常一致或者为父类方法抛出异常的子类。

    1.3自定义异常

  • 一般情况下,都是继承RuntimeException

  1. package exception_;
  2. public class CustomException {
  3. public static void main(String[] args) {
  4. int age= 120;
  5. if(!(age >= 18 && age <=70 )){
  6. throw new AgeException("年龄要在18~70之间");
  7. }
  8. System.out.println("年龄正确");
  9. }
  10. }
  11. //自定义一个异常
  12. class AgeException extends RuntimeException {
  13. public AgeException(String message) {
  14. super(message);
  15. }
  16. }