try-catch,throw和throws

发布时间:2023-05-15 09:34:40

1.try-catch连接2.try-catch练习4511

如果用户输入的不是整数,建议他反复输入,直到输入整数

com中的代码.stulzl.trycatch_exception.TryCatch_Exception
package com.stulzl.trycatch_exception;import java.util.Scanner;//如果用户输入的不是一个整数,建议他反复输入,直到输入一个整数为止  451public 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背后的异常类型可以是方法中产生的异常类型,也可以是其父类。

comm3.1快速入门代码.stulzl.throws_exception.Throws01包
package com.stulzl.throws_exception;import java.io.FileInputStream;import java.io.FileNotFoundException;//throws异常处理快速入门  452public 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.453throws异常处理的细节

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异常处理细节  453public 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子类中描述和处理。此时,您可以设计异常类来描述错误信息/span>

5.2自定义异常步骤

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

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

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

自定义异常应用实例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_try-catch

6.1练习455

try-catch,throw和throws_throw_02

com中的代码.stulzl.throw_exception.Throwexception包
package com.stulzl.throw_exception;//判断输出  455public 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(finally采用A方法);//2  //finally先输出        }    }    static void methodB() {        try {            System.out.println(进入方法B);//4            return;        } finally {            System.out.println(调用B方法的finally);//5        }    }}

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

7.章节练习7.1练习1编程题456

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

b)计算两个数相除,使用方法cal(intn1,intn2)

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);//调用方法,Arithmeticexception可能会出现除0的异常            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_System_04

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

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

7.3练习3判断输出457

try-catch,throw和throws_try-catch_06

com中的代码.stulzl.exception_homework03.包Homework03
package com.stulzl.exception_homework03;//判断输出  457public 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_自定义异常_07

7.4练习4判断输出457

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

com中的代码.stulzl.exception_homework04.包Homework04
package com.stulzl.exception_homework04;//练习4 判断输出 457public 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();    }}

上一篇 包装类
下一篇 异常的处理方式

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题