博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
BigData07_08 异常Exception
阅读量:4680 次
发布时间:2019-06-09

本文共 2152 字,大约阅读时间需要 7 分钟。

/*  作业3:题意:编写程序用于计算两个正数的加减乘除结果自定义一个异常类:MyException,当输入的数含有负数的时候,抛出自定义异常对象,并捕获处理*/import java.util.Scanner;//自定义异常类class MyException extends Exception{    public MyException(String msg){        super(msg);    }}public class ExceptionTest{    public static void main(String[] args){        //Scanner s = new Scanner(System.in);        int a = 0;        int b=0;        while(true){            System.out.println("请输入第一个数");            try{                Scanner s = new Scanner(System.in);                a = s.nextInt();                check(a);            }catch(MyException e){                    System.out.println(e.getMessage());                    System.out.println("重新输入一个数");                    continue;            }catch(Exception e ){                System.out.print("发生其他异常");                e.printStackTrace();                continue;            }            break            }        while(true){            System.out.println("请输入第二个数");            try{                Scanner s = new Scanner(System.in);                b = s.nextInt();                check(b);            }catch(MyException e){                    System.out.println(e.getMessage());                    System.out.println("重新输入一个数");                    continue;            }catch(Exception e ){                System.out.print("发生其他异常");                e.printStackTrace();                continue;            }            break            }        System.out.println("add:"+(a+b));        System.out.println("sub:"+(a-b));        System.out.println("mul:"+(a*b));        System.out.println("div:"+(a/b));    }}public static void check(int a )  throws MyException{    if(a<0){        throw new MyException("此数为负数");    }}
自定义异常 手动抛出

 

Java异常机制用到的几个关键字:trycatchfinallythrowthrows

• try        -- 用于监听。将要被监听的代码(可能抛出异常的代码)放在try语句块之内,当try语句块内发生异常时,异常就被抛出。

• catch   -- 用于捕获异常。catch用来捕获try语句块中发生的异常。

• finally  -- finally语句块总是会被执行。它主要用于回收在try块里打开的物力资源(如数据库连接、网络连接和磁盘文件)。只有finally块,执行完成之后,才会回来执行try或者catch块中的return或者throw语句,如果finally中使用了return或者throw等终止方法的语句,则就不会跳回执行,直接停止。

• throw   -- 用于抛出异常。

• throws -- 用在方法签名中,用于声明该方法可能抛出的异常。

 

 

 

 

 

转载于:https://www.cnblogs.com/star521/p/8394777.html

你可能感兴趣的文章