java:异常机制(try,catch,finally,throw,throws,自定义异常)

* String类中的格式化字符串的方法:
* public static String format(String format, Object... args):使用指定的格式字符串和参数返回一个格式化字符串。
*
* 当输入内容非整数时,将出现java.util.InputMismatchException异常(输入不匹配异常)
* 当除数为零时,出现java.lang.ArithmeticException异常。(算数异常)
* 传统的解决方案:利用if进行判断来堵漏洞(麻烦)
* 异常:程序在执行过程中遇到特殊的事件,导致程序中断执行。
* java中的异常处理: try,catch,finally,throws,throw
* 1.try...catch
* try{
* //可能出现异常的代码
* }catch(异常类型 e){
* //处理异常的代码
* }
* 执行过程:当try中代码出现异常时,将会抛出一个异常对象,
* 该异常对象会和catch中异常类型进行匹配,如果匹配成功将执行catch中的代码,否则程序中断执行。
* 异常对象中常用的方法
* printStackTrace():打印异常堆栈跟踪信息(类,消息和异常跟踪信息)
* toString():异常信息(类和消息)
* getMessage():异常消息(异常消息)

public class TestException {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入被除数:");
        int num1=0;
        int num2=0;
        int num3=0;
        try{
            num1 = input.nextInt();
            System.out.println("请输入除数:");
            num2 = input.nextInt();
            num3 = num1/num2;
        }catch(Exception e){ //(InputMismatchException e)
//            System.err.println("代码出错了...");
//            e.printStackTrace();//打印异常堆栈跟踪信息(常用)
//            System.err.println(e.toString());//toString()异常信息
            System.err.println(e.getMessage());//getMessage()获取异常消息
        }
        String str = String.format("%d/%d=%d", num1,num2,num3);
        System.out.println(str);
        System.out.println("程序执行结束!");
    }
}

 

/**
 * try...catch结构:
 * 语法:
 * try{
 *    //可能出现异常的代码
 * }catch(异常类型1 e){
 *   //处理异常类型1的代码;
 * }catch(异常类型2 e){
 *   //处理异常类型2的代码;  
 * }...
 * 执行过程与多重的if...else if条件分支类似,如果try中的代码发生的异常,将抛出一个异常对象,
 *    该异常对象会catch中的异常类型挨个进行匹配,如果匹配成功将执行catch块中的处理代码。
 * 注意:异常类型的范围应该是有小到大,否则会导致其下的catch中的代码不会执行。
 */
public class TestException3 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入被除数:");
        int num1=0;
        int num2=0;
        int num3=0;
        try{
            num1 = input.nextInt();
            System.out.println("请输入除数:");
            num2 = input.nextInt();
            num3 = num1/num2;
        }catch(InputMismatchException e){
            System.err.println("请输入数字!");
        }catch(ArithmeticException e){
            System.err.println("除数不能为零!");
        }
        String str = String.format("%d/%d=%d", num1,num2,num3);
        System.out.println(str);
        System.out.println("程序执行结束!");
    }
}

 

* try...catch...finally
* finally中的代码不论异常是否发生,永远都会执行(除非使用System.exit()退出JVM)。
* 经常将资源释放(IO流,数据库连接等)的代码放在finally中,确保资源能得到释放
* try...catch 正确
* try....catch...finally 正确
* try....finally 正确
* catch..finally 错误

public class TryCatchFinally2 {
    public static void main(String[] args) {
        try{
            System.out.println("try.....");
            int num = 4/0;
//            return;
            System.exit(1);//退出应用程序,退出JVM
        }catch(Exception e){
            System.out.println("catch....");
        }finally{
            System.out.println("finally....");
        }
    }
}

 异常有哪些:

算术异常类:ArithmeticExecption

空指针异常类:NullPointerException

类型强制转换异常:ClassCastException

数组负下标异常:NegativeArrayException

数组下标越界异常:ArrayIndexOutOfBoundsException

违背安全原则异常:SecturityException

文件已结束异常:EOFException

文件未找到异常:FileNotFoundException

字符串转换为数字异常:NumberFormatException

操作数据库异常:SQLException

输入输出异常:IOException

方法未找到异常:NoSuchMethodException

 

* throws和throw关键字.    (注意:声明异常后,内部没有try,catch,throw也不会报错)
* throws:在声明方法时声明该方法存在的异常。
* throw:在方法内部抛出异常。
* throws和throw的区别:
* 1.位置不同: throws在方法声明名用于声明该方法存在的异常,throw在方法内部用于抛出异常。
* 2.类型不同: throws后边跟的是异常类型,throw后边的异常对象
* 3.作用不同: throws的作用是告知方法的调用者该方法存在某种异常类型需要处理,
* throw的作用在用于抛出某种具体的异常对象。
* 经常throws和throw结合使用。

public class TestThrows {
    public static int divide() throws ArithmeticException{
        Scanner input = new Scanner(System.in);
        System.out.println("请输出被除数:");
        int num1 = input.nextInt();
        System.out.println("请输出除数:");
        int num2 = input.nextInt();
        int num3 =0;
        try{
            num3 =num1/num2;
        }catch(ArithmeticException e){
            throw new ArithmeticException();//相等于抛出一个异常对象
        }
        return num3;
    }
    
    public static void main(String[] args) {
        try{
            int num3 = divide();
        }catch(ArithmeticException e){
            System.err.println("除数不能为零!");
        }
    }
    
    
}

*检查异常必须进行处理,否则无法通过编译。
*常见的检查异常:
*ClassNotFoundException:类找不到异常。
*SQLException:操作SQL语句出现的异常信息
*IOException:操作IO流出现的异常信息
*....
*捕获检查异常的快捷键:1.选中出现检查异常的代码
*               2.alt+shift+z

public class TestCheckedException {
    public static void main(String[] args) {
        try {
            Class.forName("java.lang.String");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 自定义异常:

* 自定义异常:如果JDK中异常类型无法满足程序需要。
* 步骤:
* 1.编写自定义异常类:继承Exception或RuntimeException
* 2.编写构造方法,继承父类的实现
* 3.实例化自定义异常对象
* 4.使用throw抛出

 

public class AgeException extends RuntimeException{
    public AgeException(String message){
        super(message);
    }
}
public class Agezz {
    private int age;
    private int score;
    public int getAge() {
        return age;
    }
    
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    
    public Agezz() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Agezz(int age, int score) {
        super();
        this.age = age;
        this.score = score;
    }
    public  void setAge(int age)throws AgeException{
        if(age>18&&age<100){
            this.age=age;
        }else{
            throw new AgeException("不符合年龄");
        }
    }
    
    @Override
    public String toString() {
        return "Agezz [age=" + age + ", score=" + score + "]";
    }
    
}
public class Agetest {
    public static void main(String[] args) {
        Agezz a=new Agezz(0,1);
        try{
            a.setAge(0);
            
        }catch(AgeException e){
            System.out.println(e.getMessage());
        }finally{
            System.out.println("设置完成");
        }
        System.out.println(a);
    }
}

 

posted @ 2017-06-09 11:16  咫尺天涯是路人丶  阅读(380)  评论(0编辑  收藏  举报