Java try-catch-finally construct examples
- Details
- Written by Nam Ha Minh
- Last Updated on 22 August 2019   |   Print Email
To handle error/exceptions which may occur during execution of a particular code, Java introduces try-catch-finally construct. The structure of this construct is as follows:
try { // code that may throws errors/excpetions } catch (exception object is being thrown) { // code to handle exception } finally { // code always executed, regardless of exception thrown or not, // i.e clean up resources }
For example, the following code catch an exception may be thrown when parsing a number from an input string:
String input = ""; // capture input from user... int number; try { number = Integer.parseInt(input); } catch (NumberFormatException ex) { number = -1; // assigns a default value }
Some Rules about try-catch-finally construct in Java:
The catch block can be optional. The following example show only a try-finally construct:
try { number = Integer.parseInt(input); } finally { number += 100; }
The finally block is also optional, as shown in the first example. But remember that code in finally block is always executed, regardless of whether the try block throwing exception or not.
One exception for finally block is, if there is a System.exit() command executed either in the try or catch block, the finally block won't be executed. For example, in the following code, the finally block won't be executed if there is an exception thrown and the number is negative:
try { number = Integer.parseInt(input); } catch (NumberFormatException ex) { number -= 100; if (number < 0) { System.exit(0); } } finally { number += 100; }
With the release of Java SE 1.7, the try-catch statement has an additional form called try-with-resources statement.
Related Topics:
- What you may not know about the try-catch-finally construct in Java
- Java try-with-resources examples
- Java multi-catch examples
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand abstraction in Java
- Understand encapsulation in Java
- Understand inheritance in Java
- Understand polymorphism in Java
Comments