前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >异常处理

异常处理

作者头像
Qwe7
发布2022-08-05 21:47:50
9430
发布2022-08-05 21:47:50
举报
文章被收录于专栏:网络收集网络收集

抛出异常 throw

当方法执行出现问题时,方法就会创建异常对象并抛出。开发者可以在程序中自行抛出异常;JVM 在执行程序时发现问题也会自动抛出异常。

  • throw 语句:开发者自行创建异常对象并抛出,等待程序进行异常处理。
  • throws 语句:声明方法可能抛出某种异常且未经处理,调用该方法的上级需要进行异常处理。
代码语言:javascript
复制
class TestException{       
    // 把方法中的抛出异常交给上层处理     
    public void writeList(int size) throws IndexOutOfBoundsException, IOException{
        PrintWriter out = null;
        // 用户自定义异常并抛出
        if(size < 1) throw new IndexOutOfBoundsException("至少要输出1个字符");
        try{
            // 虚拟机自动发现异常也会抛出,必须出现在 try 代码块中
            out = new PrintWriter(new FileWriter(txt));
            for (int i = 0; i < size; i++)
                System.out.println("Value at: " + i + " = " + list.get(i));
        }finally{
            if (out != null) out.close();
        }
     }
}Copy to clipboardErrorCopied

捕获异常 catch

当方法执行抛出异常时,必须由专门的代码块对异常进行处理。

  • try 语句:可能出现异常的代码块。
  • catch 语句:捕获相应异常后停止执行 try 代码,转而执行对应 catch 代码。如果没有异常 catch 代码不会执行。
  • finally 语句:无论是否发生异常,finally 代码总会被执行。一般用于释放资源。

注意事项

  1. 如果 try 语句中出现的异常未被 catch,默认将异常 throw 给上层调用者处理。但必须在方法中声明 throws。
  2. try/catch 代码中的 return 语句会在执行完 finally 后再返回,但 finally 中对返回变量的改变不会影响最终的返回结果。
  3. finally 代码中应避免含有 return 语句或抛出异常,否则只会执行 finally 中的 return 语句,且不会向上级抛出异常。

Java 7 后在 try 语句中打开 IO 流,会在跳出后自动关闭流。不必再用 finally 语句关闭。

代码语言:javascript
复制
class TestException{               
    public void writeList(int size) {
        PrintWriter out = null;
        try {
            if(size < 1) throw new IndexOutOfBoundsException("至少要输出1个字符");
            out = new PrintWriter(new FileWriter("OutFile.txt"));
            for (int i = 0; i < size; i++)
                System.out.println("Value at: " + i + " = " + list.get(i));
        } catch (IndexOutOfBoundsException e) {
            System.err.println("Caught IndexOutOfBoundsException: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        } finally {
            if (out != null) out.close();
        }
    }
}

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 抛出异常 throw
  • 捕获异常 catch
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档