← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 1 of 8

Java Exception Handling Introduction

An exception is what happens when something goes wrong while a program runs, like tripping on a rock while walking. Handling it means planning what to do instead of falling.
Syntax
java
try {
    // code that may throw
} catch (ExceptionType e) {
    // handle
}

What is an Exception?

An exception is an object Java creates and throws when something disrupts a program's normal flow, like dividing by zero or accessing a null reference.

Instead of letting the program crash outright, Java lets you catch that object and decide how to respond.

Example: What is an Exception?

java
public class Main {
	public static void main(String[] args) {
		try {
			int result = 10 / 0; // throws ArithmeticException
		} catch (ArithmeticException e) {
			System.out.println("Caught: " + e.getMessage());
		}
	}
}

Checked vs Unchecked Exceptions

Checked exceptions (like IOException) must be declared or caught at compile time because the compiler forces you to acknowledge the failure is possible; unchecked exceptions (like NullPointerException) extend RuntimeException and can surface without any such warning.

Example: Checked vs Unchecked Exceptions

java
public class Main {
	public static void main(String[] args) {
		try {
			throw new RuntimeException("Unchecked"); // no need to declare it
		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
		}
	}
}

Why Handle Exceptions?

Handling exceptions keeps one failure from silently corrupting program state or crashing the whole application. It also lets you give the user a meaningful message instead of a raw stack trace, or fall back to a safe default and keep running.

Example: Why Handle Exceptions?

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Declare arr and set it to new int[2]
			int[] arr = new int[2];
			// Print a line to the console
			System.out.println(arr[5]);
		// Handle ArrayIndexOutOfBoundsException if it was thrown
		} catch (ArrayIndexOutOfBoundsException e) {
			// Print a line to the console
			System.out.println("Handled gracefully instead of crashing");
		}
	}
}

Common Exception Types

Some of the exceptions you'll hit constantly include NullPointerException (calling a method on null), ArrayIndexOutOfBoundsException (invalid array index), and ArithmeticException (like dividing an int by zero).

Recognizing these by name speeds up debugging considerably.

Example: Common Exception Types

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Declare s and set it to null
			String s = null;
			s.length();
		// Handle NullPointerException if it was thrown
		} catch (NullPointerException e) {
			// Print a line to the console
			System.out.println("Caught a NullPointerException");
		}
	}
}

The try-catch-finally Concept

The try block holds code that might fail, catch defines how to respond if it does, and finally runs regardless of whether an exception occurred — typically used to release resources like open files or network connections.

Example: The try-catch-finally Concept

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Declare result and set it to 10 / 0
			int result = 10 / 0;
		// Handle ArithmeticException if it was thrown
		} catch (ArithmeticException e) {
			// Print a line to the console
			System.out.println("Error occurred");
		// Always runs, whether or not an exception occurred
		} finally {
			// Print a line to the console
			System.out.println("Runs regardless");
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Catching Exception too broadly and hiding real bugs.
  2. Ignoring checked exceptions, which the compiler forces you to handle or declare.
  3. Leaving an empty catch block, so failures are silent.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.