博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
finally_Keyword
阅读量:3925 次
发布时间:2019-05-23

本文共 3956 字,大约阅读时间需要 13 分钟。

Java finally Block

Java Exceptions Tutorial

In the previous article, we have learned how to use Java try/catch Block to handle exceptions in Java. In this article, we will how and why to use finally block with examples.

finally, Block Overview

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether an exception is handled or not.
  • Java finally block follows try/catch block.
    For each try block, there can be zero or more catch blocks, but only one finally block.
    The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
    finally Block Different Scenario Examples
    Here is an example program that shows three methods that exit in various ways, none without executing their finally clauses:

Below example covers the below scenarios:

Throw an exception out of the method

Return from within a try block
Execute a try block normally

// Demonstrate finally.class FinallyDemo { // Throw an exception out of the method. static void procA() {    try {     System.out.println("inside procA");     throw new RuntimeException("demo");    } finally {       System.out.println("procA's finally");    } } // Return from within a try block. static void procB() {   try {     System.out.println("inside procB");     return;   } finally {     System.out.println("procB's finally");   } } // Execute a try block normally. static void procC() {   try {     System.out.println("inside procC");   } finally {     System.out.println("procC's finally");   }  } public static void main(String args[]) {   try {     procA();   } catch (Exception e) {     System.out.println("Exception caught");   }    procB();    procC();  }}

Output:

inside procAprocA's finallyException caughtinside procBprocB's finallyinside procCprocC's finally

In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is executed on the way out.

procB( )’s try statement is exited via a return statement. The finally clause is executed before procB( ) returns.
In procC( ), the try statement executes normally, without error. However, the finally block is still executed.

finally, Block Examples

Example 1: In this example, we have used FileInputStream to read the simple.txt file. After reading a file the resource FileInputStream should be closed by using finally block.

public class FileInputStreamExample {    public static void main(String[] args) {        FileInputStream fis = null;        try {            File file = new File("sample.txt");            fis = new FileInputStream(file);            int content;             while ((content = fis.read()) != -1) {               // convert to char and display it               System.out.print((char) content);            }       } catch (IOException e) {            e.printStackTrace();       } finally {           if(fis != null){               try {                   fis.close();               } catch (IOException e) {                  // TODO Auto-generated catch block                    e.printStackTrace();               }           }        }    }}

Example 2: When we use JDBC connection to communicate with a database. The resource that we have used are ResultSet, Statement, and Connection (in that order) should be closed in a finally block when you are done with them, something like that:

Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {    // Do stuff    ...} catch (SQLException ex) {    // Exception handling stuff    ...} finally {    if (rs != null) {        try {            rs.close();        } catch (SQLException e) { /* ignored */}    }    if (ps != null) {        try {            ps.close();        } catch (SQLException e) { /* ignored */}    }    if (conn != null) {        try {            conn.close();        } catch (SQLException e) { /* ignored */}    }}

转载地址:http://pbgrn.baihongyu.com/

你可能感兴趣的文章
阿星Plus:基于abp vNext开源一个博客网站
查看>>
写给自己,2020的年终总结
查看>>
Flash 生命终止,HTML5能否完美替代?
查看>>
ML.NET生成器带来了许多错误修复和增强功能以及新功能
查看>>
微信适配国产操作系统:原生支持 Linux
查看>>
我的2020年终总结:新的角色,新的开始
查看>>
C# 9 新特性 —— 增强的模式匹配
查看>>
ASP.NET Core Controller与IOC的羁绊
查看>>
如何实现 ASP.NET Core WebApi 的版本化
查看>>
探索 .Net Core 的 SourceLink
查看>>
AgileConfig-如何使用AgileConfig.Client读取配置
查看>>
【gRPC】 在.Net core中使用gRPC
查看>>
整合.NET WebAPI和 Vuejs——在.NET单体应用中使用 Vuejs 和 ElementUI
查看>>
“既然计划没有变化快,那制订计划还有个卵用啊!”
查看>>
C#实现网页加载后将页面截取成长图片
查看>>
C# 在自定义的控制台输出重定向类中整合调用方信息
查看>>
【gRPC】ProtoBuf 语言快速学习指南
查看>>
C# 9 新特性 —— 补充篇
查看>>
Asp.Net Core使用Skywalking实现分布式链路追踪
查看>>
浅谈CLR基础知识
查看>>