Coding/Learn/java/exception handling
Java Foundational Course
01.Introduction to Java
02.Your First Java Program
03.Syntax & Code Structure
04.Comments in Java
05.Variables & Declaration
06.Primitive Data Types
07.Numbers & Arithmetic Operators
08.Strings in Java
09.Booleans & Relational Operators
10.Type Casting & Conversion
11.Scanner & Interactive Input
12.Logical Operators (&&, ||, !)
13.If Statements
14.If-Else Statements
15.If-Else-If Ladders
16.Switch Statements
17.While Loops
18.Do-While Loops
19.Standard For Loops
20.Break & Continue Statements
21.Arrays in Java
22.Array Indexing & Traversal
23.Enhanced For-Each Loop
24.Essential String Methods
25.Methods in Java
26.Method Parameters & Arguments
27.Method Overloading
28.Classes & Objects in Java
29.Constructors in Java
30.Exception Handling (try-catch-finally)
31.Capstone Mini Projects
Course Certificate0%

Complete all lessons to earn

LearnException Handling (try-catch-finally)
30 / 31 0%
Lesson 30 of 31
6 mins read

Exception Handling (try-catch-finally)

PreviousNext Lesson
In Plain English

An exception is an abnormal event that occurs during execution and disrupts the normal flow of instructions. Java's robust `try-catch-finally` mechanism allows you to detect errors, handle them gracefully, and ensure cleanup code always runs.

The Mental Model

"Exception handling is like a trapeze safety net: you TRY the difficult acrobatic flip. If you slip (catch an exception), the safety net catches you safely so the show can continue, and FINALLY the stage lights are turned off at the end of the night."

Deep Dive: How It Works

`try`: Encloses code that might potentially throw an exception.

`catch (ExceptionType e)`: Catches and handles the specific error if it occurs inside the try block.

`finally`: Code that is GUARANTEED to execute, whether an exception occurred or not (used for closing files/connections).

Common exceptions: `ArithmeticException` (e.g. division by zero), `NullPointerException`, `ArrayIndexOutOfBoundsException`, `NumberFormatException`.

Syntax Blueprint

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("Cleanup always runs.");
}

Catch specific exception types. Finally block always executes.

PointCore Rules to Remember

Point star
Prevent Crashes: Handles unexpected user inputs and runtime faults gracefully.
Point star
The finally Block: Always runs regardless of try success or exception catch.
Point star
Exception Object e: e.getMessage() provides human-readable diagnostic details.

Common Beginner Traps & How to Fix Them

Mistake:Catching generic Exception before specific ones

Why it happens: Catching Exception first swallows everything, preventing specific handlers from running.

How to fix: Order catch blocks from most specific exception to most general.

Pro Tip: Use try-with-resources (e.g. try (Scanner sc = new Scanner(...)) { ... }) to automatically close streams.

Live Interactive Example

Hit Run Code to see it live
Catching Division by Zero and Number Parse Errors
Java 13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: Integer.parseInt("abc") throws NumberFormatException, which is caught and printed without crashing.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Handle array index exception

  • PointWrap the array access arr[5] in a try-catch block.
  • PointCatch ArrayIndexOutOfBoundsException e and print "Index out of range!".
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates