本文共 3956 字,大约阅读时间需要 13 分钟。
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 OverviewThrow 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.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(); } } } }}
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/