Java Exceptions - Try...Catch


Java Exceptions

When using Java code, various errors may occur: editor-generated errors, errors due to incorrect input, or other unexpected things.

In the event of an error, Java will usually stop and produce an error message. The technical term for this is: Java will issue an exception (throw an error).


Java try and catch

The try statement allows you to define a code block that will be checked for errors when done.

The catch statement allows you to specify a code block to use, in case of an error in the test block.

Try and catch keywords:


Syntax
try {
            //  Block of code to try
          }
          catch(Exception e) {
            //  Block of code to handle errors
          }
          

Consider the following example:


This will generate an error, because myNumbers[10] does not exist.

public class Main {
            public static void main(String[ ] args) {
              int[] myNumbers = {1, 2, 3};
              System.out.println(myNumbers[10]); // error!
            }
          }
          

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Main.main(Main.java:4)

In the event of an error, we can use a try ... catch to catch the error and issue a specific code to manage it:


Example
public class Main {
            public static void main(String[ ] args) {
              try {
                int[] myNumbers = {1, 2, 3};
                System.out.println(myNumbers[10]);
              } catch (Exception e) {
                System.out.println("Something went wrong.");
              }
            }
          }
          

The output will be:

Something went wrong.


Finally

The finally statement allows you to create code, after try ... catch, regardless of the result:


Example
public class Main {
            public static void main(String[] args) {
              try {
                int[] myNumbers = {1, 2, 3};
                System.out.println(myNumbers[10]);
              } catch (Exception e) {
                System.out.println("Something went wrong.");
              } finally {
                System.out.println("The 'try catch' is finished.");
              }
            }
          }
          

The output will be:

Something went wrong. The 'try catch' is finished.


The throw keyword

Throw Statement allows you to create a custom error.

The throw statement is used with a different type. There are many different types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.


Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":

public class Main {
            static void checkAge(int age) {
              if (age < 18) {
                throw new ArithmeticException("Access denied - You must be at least 18 years old.");
              }
              else {
                System.out.println("Access granted - You are old enough!");
              }
            }
          
            public static void main(String[] args) {
              checkAge(15); // Set age to 15 (which is below 18...)
            }
          }
          

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old. at Main.checkAge(Main.java:4) at Main.main(Main.java:12)

If age was 20 years old, you would find no exception:


Example
checkAge(20);
        

The output will be:

Access granted - You are old enough!