Java Exceptions: Mastering Try...Catch for Error Handling

Explore the essentials of Java exceptions and learn how to effectively use Try...Catch blocks to manage errors in your code. This guide covers common error scenarios, best practices for exception handling, and how to ensure your Java applications run smoothly despite unexpected issues. Enhance your coding skills and create robust Java applications with effective error management techniques.



Java Exceptions - Try...Catch

When executing Java code, errors can occur due to various reasons such as coding mistakes, incorrect input, or unexpected situations.

Java try and catch

The try statement allows you to test a block of code for errors while it's being executed. If an error occurs, the catch statement handles it.

Syntax

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

Consider this example:

Example

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

The output will be:

Output

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]); // Error!
} catch (Exception e) {
    System.out.println("Something went wrong.");
} finally {
    System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:

Output

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

The throw keyword

The throw statement allows you to create custom errors, known as exceptions.

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); // Throws an exception
}
}

The output will be:

Output

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 checkAge(20) is called, no exception is thrown:

Example

checkAge(20); // No exception

The output will be:

Output

Access granted - You are old enough!