Java Exception Try-Catch

Java Exception

When running Java codes, many errors can occur; coding errors made by the programmer, wrong input, and other unforseeable things.

When an error occurs, Java will normally stop the program and generate an error message. The technical term for this is : Java will throw an exception (error).

Java try-catch

  • try: The try block contains a set of statements where an exception can occur. A single try block can have several catch blocks associated with it.
  • catch: The¬†catch¬†statement allows you to define a block of code to be executed if an error occurs in the try block. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes.

Java try block must be followed by either catch or finally block. So these two code (try&catch) must come in pair.

Exception example

Look at the following example :

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

this will throw the following exception :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at MyExample.main(MyExample.java:4)

because myNumbers[5] does not exist.

try-catch example

Look at the following example:

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

This time, if an error occurs, we use the try-catch to catch the error and execute a code to handle it.

and the output will be :

Something went wrong.

Published by

Rafif Santika

The programming language that I specialize in is Java, because I think Java programming language is more universal and of course because I like it regardless of any reason.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.