🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #85

Java Exceptions


Java Exceptions

As mentioned in the Errors chapter, different types of errors can occur while running a program - such as coding mistakes, invalid input, or unexpected situations.

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


Exception Handling (try and catch)

Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.

It uses different keywords:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

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

Consider the following example:

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

If an error occurs, we can use try...catch to catch the error and execute some code to handle 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.");
    }
  }
}

Finally

The finally statement lets you execute 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 throw keyword

The throw statement allows you to create a custom error.

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

Example

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...)
  }
}

If age was 20, you would not get an exception:

Example

checkAge(20);

Errors and Exception Types

The table below shows some of the most common errors and exceptions in Java, with a short description of each:

Error/Exception Description
ArithmeticError Occurs when a numeric calculation goes wrong
ArrayIndexOutOfBoundsException Occurs when trying to access an index number that does not exist in an array
ClassNotFoundException Occurs when trying to access a class that does not exist
FileNotFoundException Occurs when a file cannot be accessed
InputMismatchException Occurs when entering wrong input (e.g. text in a numerical input)
IOException Occurs when an input or output operation fails
NullPointerException Occurs when trying to access an object referece that is null
NumberFormatException Occurs when it is not possible to convert a specified string to a numeric type
StringIndexOutOfBoundsException Occurs when trying to access a character in a String that does not exist

Tip: For a list of all errors and exception types, go to our Java Errors and Exception Types Reference.

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Java Exceptions – FAQs

Quick answers about learning Java Exceptions in Java.

This free note from CodingNow 2.0 explains Java Exceptions in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Java Exceptions, is 100% free with no signup required.
With focused practice, most students grasp Java Exceptions in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now