throws 与 throw 关键字

目录

一 、throws 关键字

二 、throw 关键字 

三 、实例 ---- throws 与 throw 的应用


 

一 、throws 关键字

 在定义一个方法时可以使用 throws 关键字声明,使用 throws 声明的方法表示此方法不处理异常,而是交给方法的调用处进行处理

【throws 使用格式】

public 返回值类型 方法名称(参数列表)throws 异常类{ }

 使用 throws 关键字

class Math{
    public int div(int i,int j) throws Exception{ //本方法不处理异常,由调用处进行处理
        int temp = i / j;    //此处有可能出现异常
        return temp;         //返回计算结果
    }
}

public class ThrowsDemo01 {
    public static void main(String[] args) {
        Math m = new Math();
        try {          //因为有throws,不管是否有异常,都必须处理
            System.out.println("除法操作:" + m.div(10,2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

程序运行结果:

提问:那么如果在主方法使用 throws 关键字呢,由谁处理异常?

class Math{
    public int div(int i,int j) throws Exception{ //本方法不处理异常,由调用处进行处理
        int temp = i / j;    //此处有可能出现异常
        return temp;         //返回计算结果
    }
}

public class ThrowsDemo01 {
    public static void main(String[] args) throws Exception{
        Math m = new Math();
        System.out.println("除法操作:" + m.div(10,2));
    }
}

因为主方法是程序的起点,此时异常由JVM处理

 

 

二 、throw 关键字 

与 throws 不同的是,可以直接使用 throw 抛出一个异常,抛出时直接抛出异常类的实例化对象

public class ThrowDemo01 {
    public static void main(String[] args) {
        try {
            throw new Exception("自己抛出的异常!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

程序运行结果:

在开发中,throws 与 throw 怎么应用呢?

 

 

三 、实例 ---- throws 与 throw 的应用

在上面的代码中,通过 throws 声明方法,如果产生异常则由调用处进行处理,但一旦出现异常,程序不会继续执行方法后面的语句,而是直接跳到调用处的catch语句中

class Math{
    public int div(int i,int j) throws Exception{ //本方法不处理异常,由调用处进行处理
        System.out.println("------计算开始------");
        int temp = i / j;    //此处有可能出现异常
        System.out.println("------计算结束------");  //如果产生了异常,程序将不会执行到此语句
        return temp;         //返回计算结果
    }
}

public class ThrowsDemo01 {
    public static void main(String[] args) throws Exception{
        Math m = new Math();
        try {
            System.out.println("除法操作:" + m.div(10,0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

程序运行结果:

 

 提问:如果有这样的需求:如果产生异常就交给调用处进行处理,而方法继续执行,该怎么做呢?

回答:通过 try....catch....finally、throw、throws联合使用

class Math{
    public int div(int i,int j) throws Exception{  //本方法不处理异常,由调用处进行处理
        System.out.println("------计算开始------");
        int temp = 0;
        try {
            temp = i / j;    //此处有可能出现异常
        }catch (Exception e){
            throw e;      //如果产生异常,则抛给调用处
        }finally {
            System.out.println("------计算结束------"); //继续执行方法的语句
        }
        return temp;         //返回计算结果
    }
}

public class ThrowsDemo02 {
    public static void main(String[] args) throws Exception{
        Math m = new Math();
        try {
            System.out.println("除法操作:" + m.div(10,0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

程序运行结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章