throw 和 throws 的区别、及处理方式?

throw:

  • 表示方法内抛出某种异常对象
  • 如果异常对象是受检异常( 非RuntimeException ),则需要在方法申明时加上该异常的抛出,即需要加上throws 语句 或者 在方法体内 try-catch 处理该异常,否则编译报错
  • 执行到 throw 语句则后面的语句块不再执行

throws:

  • 方法的定义上使用 throws 表示这个方法可能抛出某种异常
  • 需要由方法的调用者进行异常处理

异常处理方式:

  • 抛出 throws
  • 捕捉 try-catch-finally

什么时候定义try,什么时候定义throws?

  • 方法内部如果出现异常,可以处理则用try;
  • 如果方法内部不能处理,就必须声明出来,让调用者处理【受检异常】

下面就用代码来理解知识点

import java.io.IOException;

public class Demo_1 {
    
    
    public static void main(String[] args) throws NullPointerException{
    
    
        testThrows();

        Integer i = null;
        testThrow(i);

        //受检异常
        String s = null;
        try {
    
    //可以直接捕捉 或者 直接调用者抛出throws
            testThrow(s);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 测试throws关键字
     */
    public static void testThrows() throws NullPointerException{
    
    
        Integer i = null;
        System.out.println(i + 1);
    }

    /**
     * 测试throw关键字抛出 运行时异常(非受检异常)
     * @param i
     */
    public static void testThrow(Integer i){
    
    
        if(i == null){
    
    
            throw new NullPointerException();//运行时异常(非受检异常)不需要在方法上申明
        }
    }

    public static void testThrow(String s) throws IOException {
    
    
        if(s == null){
    
    
            throw new IOException();//非运行时异常(受检异常)需要在方法上声明,最终可由调用者处理
        }
    }
}

总结:

  • throw:用于抛出异常对象,后面跟着是异常对象;throw用在方法体内;
  • throws:用于抛出异常,后面跟着是异常类名,可以跟多个,用逗号隔开;throws用在方法上;
  • 受检异常必须进行处理,可以抛出也可以直接捕捉;
  • 异常处理方式:抛出throws、捕捉try-catch-finally。

猜你喜欢

转载自blog.csdn.net/weixin_46312449/article/details/113179985