Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Introduction to Exceptions

Last Updated: 22nd March, 2026

5.1 Introduction to Exceptions

5.1.1 Explanation

An exception in Java is an event that disrupts the normal flow of a program’s execution. It represents an error or an unexpected condition that occurs during runtime — such as invalid user input, file access failure, or division by zero.

Java provides a robust exception handling mechanism to maintain program stability and ensure graceful error recovery instead of abrupt termination.
All exception classes are derived from the base class Throwable, which has two major subclasses:

  • Exception (recoverable errors, e.g., file not found, invalid input)
  • Error (serious system failures, e.g., memory overflow, JVM crash)

Within the Exception hierarchy, we distinguish between:

  • Checked Exceptions: Must be declared in a method’s throws clause or handled using try-catch (e.g., IOException, SQLException).
  • Unchecked Exceptions: Arise from logical or programming errors and don’t require mandatory handling (e.g., NullPointerException, ArithmeticException).

Proper exception handling improves software robustnessuser experience, and security, ensuring applications recover or fail safely.

5.1.2 Code

public class ExceptionExample {

public static void main(String[] args) {

try {

int result = 10 / 0; // Division by zero causes ArithmeticException

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero!");

} finally {

System.out.println("Execution completed.");

}

}

}

5.1.3 Example

Output:

Error: Cannot divide by zero!

Execution completed.

Explanation:
The program attempts to divide by zero, triggering an ArithmeticException.
The catch block captures and handles it, preventing abrupt program termination.
The finally block executes regardless of success or failure, typically used for resource cleanup.

5.1.4 Use Cases

  • Handling database or file I/O failures gracefully.
  • Preventing application crashes due to invalid user input.
  • Ensuring network programs handle disconnections safely.
  • Managing external API call failures with fallback mechanisms.

5.1.5 Relevant Table

Type

Description

Examples

Checked

Compile-time checked exceptions

IOExceptionSQLException

Unchecked

Runtime exceptions

NullPointerExceptionIndexOutOfBoundsException

Error

Severe system-level issue

OutOfMemoryErrorStackOverflowError

5.2 Handling Exceptions

5.2.1 Explanation

Java’s exception handling mechanism revolves around five key keywords:

  1. try — encloses code that might throw an exception.
  2. catch — handles specific exceptions.
  3. finally — executes cleanup code, regardless of exception.
  4. throw — manually throws an exception.
  5. throws — declares exceptions that a method might throw.

The try-catch-finally construct ensures smooth error handling and resource management.
When multiple exceptions may occur, multi-catch blocks can be used to handle them efficiently.
Nested try-catch statements allow localized handling in complex programs.

Java also introduced try-with-resources (Java 7+) — a modern structure that automatically closes resources like files, sockets, or streams, avoiding memory leaks and resource exhaustion.

5.2.2 Code

import java.io.*;

public class FileReadExample {

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {

String line;

while ((line = br.readLine()) != null) {

System.out.println(line);

}

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

} catch (IOException e) {

System.out.println("I/O Error: " + e.getMessage());

} finally {

System.out.println("File operation completed.");

}

}

}

5.2.3 Example

Output:

File not found: data.txt (No such file or directory)

File operation completed.

Explanation:
This code reads from a file using the try-with-resources statement, which automatically closes the BufferedReader.
If the file is missing, a FileNotFoundException is caught, and the error is logged gracefully.

5.2.4 Use Cases

  • Ensuring files or streams are always closed after use.
  • Managing user inputs, data validation, and configuration errors.
  • Protecting APIs from unhandled exceptions that might expose system internals.
  • Building reliable, fault-tolerant systems.

5.2.5 Relevant Table

Keyword

Purpose

Example

try

Encloses code that may throw exception

try { risky(); }

catch

Handles exception type

catch(IOException e)

finally

Executes cleanup

finally { close(); }

throw

Manually throw exception

throw new Exception("Error");

throws

Declares exception propagation

void read() throws IOException

5.3 Custom Exceptions

5.3.1 Explanation

In enterprise Java systems, predefined exceptions may not describe domain-specific errors precisely. Hence, Java allows developers to create custom exception classes by extending the Exception or RuntimeException class.

Custom exceptions enhance clarity and semantic error reporting, providing meaningful messages to users and developers.
They can represent specific business conditions — for example, InsufficientFundsException in banking systems or InvalidAgeException in registration systems.

The best practice is to extend Exception for checked exceptions (forcing handling) and RuntimeException for unchecked exceptions (optional handling).
Custom messages and constructors help pass additional error context for debugging and logging.

5.3.2 Code

class InvalidAgeException extends Exception {

InvalidAgeException(String message) {

super(message);

}

}

public class CustomExceptionDemo {

static void validateAge(int age) throws InvalidAgeException {

if (age < 18)

throw new InvalidAgeException("Access denied: Age must be 18 or above.");

else

System.out.println("Access granted.");

}

public static void main(String[] args) {

try {

validateAge(15);

} catch (InvalidAgeException e) {

System.out.println("Exception caught: " + e.getMessage());

}

}

}

5.3.3 Example

Output:

Exception caught: Access denied: Age must be 18 or above.

Explanation:
The InvalidAgeException is a user-defined exception that extends Exception.
When the validateAge() method detects a rule violation, it throws a descriptive custom message.

5.3.4 Use Cases

  • Defining domain-specific error handling (e.g., insufficient balance).
  • Providing descriptive messages for debugging and logging.
  • Implementing strict validation in user input or database systems.
  • Creating modular and maintainable exception frameworks.

5.3.5 Relevant Table

Exception Type

Base Class

Checked/Unchecked

Example

Custom Business Exception

Exception

Checked

InvalidOrderException

Validation Error

RuntimeException

Unchecked

EmptyFieldException

Access Violation

Exception

Checked

AccessDeniedException

Module 5: Exception Handling and File ManagementIntroduction to Exceptions

Top Tutorials

Logo
Computer Science

CNN in Deep Learning 2026

A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.

4 Modules12 Lessons151 Learners
Start Learning
Logo
Computer Science

Breaking The Limits: Scaling Databases with MySQL Partitioning

Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.

7 Modules11 Lessons71 Learners
Start Learning
Logo

ML in Action: Hands-On Guide to Deploying and Serving Models

Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.

4 Modules10 Lessons78 Learners
Start Learning
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2026 AlmaBetter