Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Exception

Java Exceptions

During the execution of Java code, various errors may arise, including coding errors made by the programmer, errors stemming from incorrect input, or unforeseen circumstances.

When an error arises, Java typically halts and generates an error message. This process is technically termed as Java throwing an exception (or throwing an error).

Java try and catch

The try statement enables you to specify a block of code to be evaluated for errors during its execution.

The catch statement permits you to specify a block of code to be executed if an error arises within the try block.

The try and catch keywords are used in pairs.

Syntax

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

Take into account the following example:

An error will be triggered 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 is expected to resemble the following:

Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 10

       
at Main.main(Main.java:4)

In the event of an error, we can employ try…catch to capture the error and execute 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 is expected to be:

Something went wrong.

Finally

The finally statement enables the execution of code after try…catch, regardless of the outcome:

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 is expected to be:

Something went wrong.

The ‘try-catch’ block has completed.

The throw keyword

The throw statement permits you to generate a custom error.

The throw statement is employed alongside an exception type. Java offers numerous exception types, including ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and more.

Example

If the age is below 18, throw an exception (print “Access denied”). Otherwise, if the 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 expected output is:

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 the age were 20, no exception would be encountered.

Example

checkAge(20);

The expected output is:

Access granted - You are old enough!