欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

深入理解Java编程:第三十二讲 - 如何运用throw语句抛出异常

最编程 2024-07-23 12:06:54
...

如果需要在程序中自行抛出异常,则应使用 throw 语句。throw 吾句可以单独使用,throw 语句抛出的不是异常类,而是一个异常实例,而且每次只能抛出一个异常实 throw 语句的语法格式如下:

throw ExceptionInstance ;

ThrowTest.java

public class ThrowTest{
  public static void main(String[] args){
    try{
      // 调用声明抛出Checked异常的方法,要么显式捕获该异常
      // 要么在main方法中再次声明抛出
      throwChecked(-3);
    }catch (Exception e){
      System.out.println(e.getMessage());
    }
    // 调用声明抛出Runtime异常的方法既可以显式捕获该异常,
    // 也可不理会该异常
    throwRuntime(3);
  }
  public static void throwChecked(int a)throws Exception{
    if (a > 0){
      // 自行抛出Exception异常
      // 该代码必须处于try块里,或处于带throws声明的方法中
      throw new Exception("a的值大于0,不符合要求");
    }
  }
  public static void throwRuntime(int a){
    if (a > 0){
      // 自行抛出RuntimeException异常,既可以显式捕获该异常
      // 也可完全不理会该异常,把该异常交给该方法调用者处理
      throw new RuntimeException("a的值大于0,不符合要求");
    }
  }
}

推荐阅读