CodeGym /Java Blog /Java Exceptions /Java Try - Catch
Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Java Try - Catch

Published in the Java Exceptions group
Errors can occur during program executing. It’s a common problem for every programmer, from a beginner to a real pro. Not all errors arise through the fault of the developer. Some of them are difficult to predict, and sometimes it’s not possible. For example, while downloading a program, the network connection may suddenly drop or the power may go out. Such situations are called exceptions. Try and catch are the parts of construction used for handling exceptions.

Java try and catch block

When an error occurs, Java usually stops and generates an error message. This process is called "Java throws an exception". Java provides special facilities for handling exceptions. One of them is try...catch...finally construction. Here is the syntax of try block, catch block and finally block.

//try block
try {
  // Block of code to try
}
//try catch 
catch(Exception e) {
  // Block of code to handle errors
}
finally {
 // Optional block of code 
          }
When an exception occurs in the try block, control passes to the catch block, which can handle the exception. If no such block is found, an unhandled exception message is displayed to the user and further execution of the program is stopped. It is to prevent such an emergency stop that you need to use the try..catch block. Java Try - Catch - 1

Briefly about try, catch, finally, throws keywords

Exception handling in Java is based on the use of the following keywords in a program:
  • try — defines a block of code in which an exception can occur;
  • catch — defines the block of code in which the exception is handled;
  • finally — defines a block of code that is optional, but if present, is executed anyway, regardless of the results of the try block.
These keywords are used to create special processing constructs in the program code: try catch, and try catch finally}.
  • throw — used to raise an exception;
  • throws — used in method signatures to warn that a method might throw an exception.

Easy example of try-catch construction

Let's say we have a program with some array.

public class TryTest {
   public static void main(String[] args) {
       int[] myArray = new int[5];
       myArray[7] = 8;
       System.out.println(myArray[7]);
   }
}
Since we are trying to access an array element with a non-existent index, the program will exit with an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:6) Process finished with exit code 1
Let's modify this program and handle this exception with a try-catch. First comes try block, later — catch block.

//try catch example
public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (Exception myEx) {
           System.out.println("The exception was handled...");
       }

       System.out.println("This is the end of the program...");
   }
}
Now the output has changed:
The exception was handled... This is the end of the program... Process finished with exit code 0 Process finished with exit code 0
In this case, the program completed correctly, our message is displayed on the screen. The correct termination of the program is signaled by code 0 at the end of the process, while incorrect — 1. When using a try...catch block, all statements between the try and catch statements are executed first. If an exception occurs in the try block, then the normal execution order stops and proceeds to the catch statement. Therefore, when the program execution reaches the numbers[7]=8; line, the program will stop and go to the catch block In our case, we have declared the variable myEx with the type Exception. This is the base class for all exceptions, and so they can be different. For example, there are exceptions that are responsible for stack overflows, going beyond the array indexing, as in our case, pointing to Null, and so on. If we hadn't guessed with the type of exception, then the program would also have terminated incorrectly. However, we chose the Exception type for simplicity of the example, and it is the base class for all exceptions. So the catch statement (Exception myEx) will handle almost all exceptions. Handling the exception in this case After the catch block completes, the program continues its work, executing all other instructions after the catch block. If you want to see occurred exceptions, you can have the program print a stack trace of method calls. This is what the JVM does when an uncaught exception occurs: it stops the execution of the program, and prints a stack trace after executing the code of the finally block, if present.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (Exception myEx) {
          
         myEx.printStackTrace();
       }

       System.out.println("This is the end of the program...");
   }
}
Handling the exception in this case comes down to printing the error trace stack to the console using the printStackTrace() method defined in the Exception class.
java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:7) This is the end of the program... Process finished with exit code 0
However, the program exited correctly.

Finally! After catching

In the example and in the definitions of the key words for exception handling, we mentioned the finally block. It is optional, but if present, it will be executed regardless of the results of the try block. Let's change the exception type to NullPointerException.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (NullPointerException myEx) {
           System.out.println("The exception was handled...");

       }

       finally{
           System.out.println(" finally");
       }

       System.out.println("This is the end of the program...");
   }
}
Here is the output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5 at days.TryTest.main(TryTest.java:7) finally Process finished with exit code 1
By the way, we can specify the type of exception to be correct. Here it is IndexOutOfBoundsException.

public class TryTest {
   public static void main(String[] args) {
       try {
           int[] myArray = new int[5];
           myArray[7] = 8;
           System.out.println(myArray[7]);
       } catch (IndexOutOfBoundsException myEx) {
           System.out.println("The exception was handled...");

       }

       finally{
           System.out.println(" finally");
       }

       System.out.println("This is the end of the program...");
   }
}
In this case, the output will be as follows:
The exception was handled... finally This is the end of the program... Process finished with exit code 0
Java Try - Catch - 2

What’s the way exceptions work?

The point is that all these words —catch, throw, throws can only be used with java.lang.Throwable or its descendants. For example, you can do this:

public class MyClass {
    public static void main(String[] args) {
        try {
        } catch (Throwable thr) {
}
    }
}
However, you can't do it like this:

public class MyClass {
public static void main(String[] args) {
        try {
        } catch (String thr) {
}
    }
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION