
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Examples - Use of Finally
Problem Description
How to use finally block for catching exceptions ?
Solution
This example shows how to use finally block to catch runtime exceptions (Illegal Argument Exception) by the use of e.getMessage().
public class ExceptionDemo2 { public static void main(String[] argv) { new ExceptionDemo2().doTheWork(); } public void doTheWork() { Object o = null; for (int i = 0; i < 5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println("Error: ("+ e.getMessage()+")."); return; } finally { System.err.println("All done"); if (o == null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1)throw new IllegalArgumentException("Don't like type " + type); return new Object(); } }
Result
The above code sample will produce the following result.
All done java.lang.Object@1b90b39 Error: (Don't like type 1). All done
The following is an another sample example of finally block in java
public class HelloWorld { public static void main(String []args) { try { int data = 25/5; System.out.println(data); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } }
The above code sample will produce the following result.
5 finally block is always executed rest of the code...
java_exceptions.htm
Advertisements