高级异常

一、什么是异常

  解析:异常就是在程序的运行过程中所发生的不正常事件

二、Java异常处理是通过5个关键字来解决的:try、catch、finally、(前三个是捕获异常)throw(手动抛出异常)、throws(声明异常)。

三、1)try-catch块

public class Text3 {

    /**
     * @param args
     *1、 Java的异常处理是通过五个关键字来实现的:
     * try、catch、finally、throw、throws
     *2、 e.printStackTrace();//输出异常的堆栈信息
     * 3、String getMessage():返回异常信息描述字符串
     *     字符串描述异常产生的原因是:printStackTrace()输出信息的一部分
     * 4、使用Try-catch如果有输入错误那么到哪一行以后忽略其它行直接进入
     *     catch块中执行
     */
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.println("请输入被除数:");
        try {
            int num=input.nextInt();
            System.out.println(num);
            System.out.println("请输入除数");
            int num1=input.nextInt();
            System.out.println(String.format("%d/%d=%d",num,num1,num/num1));
            System.out.println("感谢使用本程序");
        } catch (Exception e) {
        System.err.print("出现错误被除数和除数;必须都是整数,"+"除数不能为0");
        e.printStackTrace();//输出异常的堆栈信息
        }

 2)多重catch

package cn.happy.lianxi;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Text5 {
    /**
     * @param args
     * catch(Exception e)--------->排列顺序必须是从子类到父类
     */
private void mian() {
    Scanner input=new Scanner(System.in);
    System.out.println("请输入被除数:");
    try {
        int num=input.nextInt();
        System.out.println(num);
        System.out.println("请输入除数");
        int num1=input.nextInt();
        System.out.println(String.format("%d/%d=%d",num,num1,num/num1));
        System.out.println("感谢使用本程序");
    }catch(InputMismatchException e){
        System.out.println("输入的被除数和除数必须都是整数");
    }catch(ArithmeticException e){
        System.out.println("除数不能为零");
    }catch(Exception e){
        System.out.println("其它未知异常");
    }finally{
        System.out.println("感谢使用本程序");
    }

}
}

3)try-catch-finally

package cn.happy.lianxi;

public class TText1 {
    
    /*
     * System.exit(1);            jvm异常退出
     * System.exit(0);            正常退出
     * try---catch---finally  捕获异常
     * throw     抛出异常
     * throws    声明异常
     * 
     * 
     * 
     * */
    
                                        //声明异常或者用try---catch
public static void main(String[] args) throws Exception {
    try {
        int result=5/0;
        System.out.println(result);
    } catch (Exception e) {
        System.out.println("错误");
    }
    

4)throw----throws

package cn.happy.lianxi;

public class ClaTT {
                                    //声明异常
 public void Cal(int num,int num1) throws Exception{
     if(num1==0)
         //抛出异常
         throw new Exception ("除数不能为0");
     else{
        int result=num/num1;
        System.out.println(result);
     }
 }
 
}

注意点:

  1、一般情况下都会走finally块,只有在如下情况下不会走到

try{
//代码
}catch(Exception e){

    System.exit(0);        //正常退出
}finally{

    System.out.print("不会finally代码块");
}

  四、异常的分类

  

原文地址:https://www.cnblogs.com/yejiaojiao/p/5431796.html