1. try-catch接上

2. try-catch练习  451

如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止

代码在com.stulzl.trycatch_exception.包中

TryCatch_Exception

package com.stulzl.trycatch_exception;

import java.util.Scanner;

//如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止  451
public class TryCatch_Exception {
    public static void main(String[] args) {
        //如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止
        //思路
        //1. 创建 Scanner 对象
        //2. 使用无限循环,去接收一个输入
        //3. 然后将该输入的值,转成一个 int
        //4. 如果在转换时,抛出异常,说明输入的内容不是一个可以转成 int 的内容
        //5. 如果没有抛出异常,则 break 该循环
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        String input = "";
        while(true){
            System.out.println("请输入一个整数:");
            input = scanner.next();
            try {
                num = Integer.parseInt(input);//这里如果输入的不是整数,抛出异常
                break;//是整数则跳出循环
            } catch (NumberFormatException e) {
                System.out.println("你输入的不是一个整数");
            }
        }
        System.out.println("你输入的整数为:"+num);
    }
}

3. throws异常处理介绍  452

1)如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。

2)在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。

3.1 快速入门

代码在com.stulzl.throws_exception.包中

Throws01
package com.stulzl.throws_exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

//throws异常处理快速入门  452
public class Throws01 {
    public static void main(String[] args) {

    }
                          //throws关键字后也可以是 异常列表,既可以抛出多个异常
    public void f1() throws FileNotFoundException,NullPointerException,ArithmeticException{
        //创建一个文件流对象
        //解读
        //这里的额异常是一个FileNotFoundExceptionn编译异常
        //解决办法
        //1. 使用try-catch-finally
        //2. 使用throws抛出异常,让调用f2方法的调用者(方法)处理
        //throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类
        //throws关键字后也可以是 异常列表,既可以抛出多个异常
        FileInputStream fis = new FileInputStream("d://aa.txt");
    }
}

4. throws异常处理的细节  453

1)对于编译异常,程序中必须处理,比如try-catch或者throws

2)对于运行时异常,程序中如果没有处理,默认就是throws的方式处理[举例]

3)子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常的类型的子类型[举例]

4)在throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws

代码在com.stulzl.throws_exception_detail.包中

ThrowsDetail
package com.stulzl.throws_exception_detail;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

//throws异常处理细节  453
public class ThrowsDetail {
    public static void main(String[] args) {

    }
    public void f2() /*throws ArithmeticException 默认的 */{
        //1)对于编译异常,程序中必须处理,比如try-catch或者throws
        //2)对于运行时异常,程序中如果没有处理,默认就是throws的方式处理[举例]
        int n1 = 10;
        int n2 = 0;
        double res = n1/n2;
    }
    
    public static void f1() throws FileNotFoundException {
    //这里大家思考问题 调用 f3() 报错
    //   解读
    //1. 因为 f3() 方法抛出的是一个编译异常
    //2. 即这时,f1()引用f3(),就相当于f1(),有一个编译异常,就要 f1() 必须处理这个编译异常
    //3. 在 f1() 中,要么 try-catch-finally ,或者继续 throws 这个编译异常解决这个编译异常
        f3(); // 抛出异常
    }
    public static void f3() throws FileNotFoundException {//抛出“编译”异常,注意是编译异常
        FileInputStream fis = new FileInputStream("d://aa.txt");
    }

    public static void f4() {
    //   解读:
    //1. 在 f4()中调用方法 f5() 是 OK
    //2. 原因是 f5() 抛出的是运行异常
    //3. 而 java 中,并不要求程序员显示处理,因为有默认处理机制
        f5();
    }
    public static void f5() throws ArithmeticException {//抛出”运行“异常
    }
}

class Father{//父类
    public void method() throws RuntimeException {
    }
}
class son extends Father{//子类
    //3)子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型
    // 要么和父类抛出的异常一致,要么为父类抛出的异常的类型的子类型[举例]
    //4)在throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws
    @Override
    public void method() throws ArithmeticException {
    }
}

5. 自定义异常

5.1 基本介绍

当程序中出现了某些"错误”,但该错误信息并没有在Throwable子类中描述处理,这个时候可以自己设计异常类,用于描述该错误信息。

5.2 自定义异常的步骤

1)定义类:自定义异常类名(程序员自己写)继承Exception或RuntimeException

2)如果继承Exception,属于编译异常

3)如果继承RuntimeException,属于运行异常(一般来说,继承RuntimeException)

5.3 自定义异常应用实例  454

当我们接收Person对象年龄时,要求范围在18- 120之间,否则抛出一个自定义异常(要求继承RuntimeException),并给出提示信息。

代码在com.stulzl.custom_exception.包中

CustomException

package com.stulzl.custom_exception;

//当我们接收Person对象年龄时,要求范围在18- 120之间,否则抛出   454
// 一个自定义异常(要求继承RuntimeException),并给出提示信息。
public class CustomException {
    public static void main(String[] args) {
        int age = 10;
        //要求范围在 18 – 120 之间,否则抛出一个自定义异常
        if(!(age>=18 && age<=120)){
            //这里我们可以通过构造器,设置信息
            throw new AgeException("年龄需要在18-120之间");
        }
        System.out.println("年龄范围正确");
    }
}

//自定义异常
//   解读
//1. 一般情况下,我们自定义异常是继承 RuntimeException
//2. 即把自定义异常做成 运行时异常,好处时,我们可以使用默认的处理机制
//3. 即比较方便
class AgeException extends RuntimeException{
    //构造器
    public AgeException(String message) {
        super(message);
    }
}

6. 一览表

try-catch,throw和throws_抛出异常

6.1 练习  455

try-catch,throw和throws_try-catch_02

代码在com.stulzl.throw_exception.包中

ThrowException
package com.stulzl.throw_exception;

//判断输出  455
public class ThrowException {
    public static void main(String[] args) {
        try {
            ReturnExceptionDemo.methodA();
        } catch (Exception e) {//捕获异常
            System.out.println(e.getMessage());//输出捕获的异常信息也就是3
        }
        ReturnExceptionDemo.methodB();
    }
}
class ReturnExceptionDemo {
    static void methodA() {
        try {
            System.out.println("进入方法A");//1
            throw new RuntimeException("制造异常");//3 //这里是抛出异常对象
        } finally {
            System.out.println("用A方法的finally");//2  //finally先输出
        }
    }

    static void methodB() {
        try {
            System.out.println("进入方法B");//4
            return;
        } finally {
            System.out.println("调用B方法的finally");//5
        }
    }
}

try-catch,throw和throws_throw_03

7. 章节练习

7.1 练习1  编程题   456

a)编写应用程序,接收命令行的两个参数(整数),计算两数相除。

b)计算两个数相除,要求使用方法cal(int n1, int n2)

c)对数据格式不正确(NumberformatException)、 缺少命令行参数(ArrayIndexOutOfBoundsException)、除0进行异常处理(ArithmeticException)。

这里提示一下 接收命令行参数是从main(String[] args)中的args中取得

代码在com.stulzl.exception_homework01.包中

Homework01

package com.stulzl.exception_homework01;

//a)接收命令行的两个参数(整数),计算两数相除。
//b)计算两个数相除,要求使用方法cal(int n1, int n2)
//c)对数据格式不正确(NumberFormatException)、
// 缺少命令行参数(ArrayIndexOutOfBoundsException)、除0进行异常处理(ArithmeticException)。
public class Homework01 {
    public static void main(String[] args) {
        try {
            //接收命令行的两个参数(整数),注意是命令行也就是args中取
            //先验证参数的个数是否正确,两个参数
            if(args.length!=2){
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            }
            
            //先把接受的参数转成整数
            int n1 = Integer.parseInt(args[0]);//这里将输入的数据转为整数,当输出数据不能转是抛出异常
            int n2 = Integer.parseInt(args[1]);

            double res = cal(n1,n2);//调用方法,可能会出现除0的异常ArithmeticException
            System.out.println("计算结果是="+res);

        } catch (ArrayIndexOutOfBoundsException e) {//捕获参数个数异常
            System.out.println(e.getMessage());//输出参数不对异常提示
        }catch(NumberFormatException e){//捕获数据格式异常
            System.out.println("参数格式不正确,需要输出整数");
        }catch(ArithmeticException e){//捕获数据计算异常
            System.out.println("出现了除0的异常");
        }
    }
    
    //方法
    public static double cal(int n1, int n2){
        return n1/n2;
    }
}

7.2 练习2 判断输出  457

try-catch,throw和throws_抛出异常_04

代码在com.stulzl.exception_homework02.包中

Homework02

package com.stulzl.exception_homework02;

//判断输出 457
public class Homework02 {
    public static void main(String[] args) {
        //args.length = 0
        //这里发生的是 ArrayIndexOutOfBoundsException
        if(args[4].equals("john")){  //可能发生NullPointerException
            System.out.println("AA");
        }else{
            System.out.println("BB");
        }
        Object o= args[2]; //String->Object ,向上转型
        Integer i = (Integer)o; //错误,这里一定会发生 ClassCastException异常

    }
}

try-catch,throw和throws_try-catch_05

7.3  练习3 判断输出  457

try-catch,throw和throws_抛出异常_06

代码在com.stulzl.exception_homework03.包中

Homework03

package com.stulzl.exception_homework03;

//判断输出  457
public class Homework03 {
    public static void main(String[] args) {
        try {
            func();
            System.out.println("A");//不输出
        } catch (Exception e) {//捕获异常
            System.out.println("C");
        }
        System.out.println("D");
    }
    public static void func() {//静态方法
        try {
            throw new RuntimeException();//抛出异常
        } finally {
            System.out.println("B");//finally先输出
        }
    }
}

try-catch,throw和throws_throw_07

7.4 练习4 判断输出 457 

try-catch,throw和throws_System_08

代码在com.stulzl.exception_homework04.包中

Homework04

package com.stulzl.exception_homework04;

//练习4 判断输出 457
public class Homework04 {
    public static void main(String[] args) {
        try {
            showExce();
            System.out.println("A");
        } catch (Exception e) {
            System.out.println("B");
        } finally {
            System.out.println("C");
        }
        System.out.println("D");
    }
    public static void showExce() throws Exception {
        throw new Exception();
    }
}

try-catch,throw和throws_自定义异常_09