Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Try-Catch Blocks

Code Description:

If code has the potential to throw an exception, it can be handled with a Try-Catch block. The Try-Catch block will allow for a program to not terminate abruptly if an exception/error is thrown. The Try block is used to encase code that may throw an exception when execution is attempted. If an exception is thrown, the rest of the Try block is skipped and the code that is in the Catch block is executed. If the code in the Try block runs properly, the Catch block's code will not run. The Finally block, which is optional, is used to execute statements regardless of if the Try block was successful or the Catch block was executed.

In our runnable example code, we cause an exception or error by trying to set a value of an Array that does not exist. Our array holds 3 elements but we are trying to set the value for element 10. Since the error generates, the Try block fails and we move into the Catch block immediately. The Finally block then executes after the Catch block is finished. This error would have normally stopped your application from running but since it was handled, your application finished execution properly.

Try-Catch Syntax:

try {
    // This code will attempt to execute.
} catch (Exception e) {
    // If the code above fails, this executes.
} finally {
    // This will execute no matter what.

Runnable Try-Catch Example Code:

public class Demo {

    public static void main(String[] args) {
	try {
	    String[] stringArray = new String[3];
	    stringArray[10] = "String";
	    System.out.println("Try Succeeded");
	} catch (Exception e) {
	    System.out.println("Try Failed");
	} finally {
	    System.out.println("Finally Executed");

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.


When the Try-Catch Block is Used:

Try-Catch Block Output Image

Without the Try-Catch Block - Error:

Error Output Image without Try-Catch Block

Important Methods:

  • printStackTrace() - Used in the Catch block to print out the error that occurred and where it came from. EX: "e.printStackTrace();"

Related Links:

Array Data Structures Java Methods