Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Mastering Exception Handling in Java: A Comprehensive Guide

Mastering Exception Handling in Java: A Comprehensive Guide

Date- Mar 16,2026 44
java exception handling

Overview of Exception Handling

Exception handling is a powerful mechanism in Java that allows developers to manage errors and exceptional conditions in a controlled manner. It ensures that the program can continue executing or gracefully terminate without crashing. Understanding how to handle exceptions is crucial for writing robust, maintainable code that enhances user experience by dealing with unexpected scenarios effectively.

Prerequisites

  • Basic understanding of Java programming
  • Familiarity with Java syntax and control structures
  • Knowledge of classes and objects in Java
  • Basic understanding of debugging techniques

Types of Exceptions in Java

Java categorizes exceptions into two main types: checked exceptions and unchecked exceptions.

Checked Exceptions

Checked exceptions are exceptions that must be either caught or declared in the method signature. They are checked at compile-time.

import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("non_existing_file.txt");
        } catch (IOException e) {
            System.out.println("Caught a checked exception: " + e.getMessage());
        }
    }
}

This code demonstrates how to handle a checked exception:

  • import java.io.FileReader; - Imports the FileReader class for reading files.
  • import java.io.IOException; - Imports the IOException class for handling input/output exceptions.
  • public class CheckedExceptionExample { - Defines the main class.
  • public static void main(String[] args) { - The main method where execution starts.
  • try { - Begins the try block to attempt risky operations.
  • FileReader file = new FileReader("non_existing_file.txt"); - Attempts to open a non-existing file, which throws an IOException.
  • } catch (IOException e) { - Catches the IOException if it occurs.
  • System.out.println(...); - Prints the message associated with the exception.
  • } - Closes the catch block and main method.

Unchecked Exceptions

Unchecked exceptions are not required to be caught or declared. They are checked at runtime.

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught an unchecked exception: " + e.getMessage());
        }
    }
}

This code illustrates an unchecked exception:

  • public class UncheckedExceptionExample { - Defines the main class.
  • public static void main(String[] args) { - The main method where execution starts.
  • int[] numbers = {1, 2, 3}; - Declares an array of integers.
  • try { - Starts the try block.
  • System.out.println(numbers[5]); - Attempts to access an invalid index, which throws an ArrayIndexOutOfBoundsException.
  • } catch (ArrayIndexOutOfBoundsException e) { - Catches the unchecked exception.
  • System.out.println(...); - Prints the exception message.
  • } - Closes the catch block and main method.

Throwing Exceptions

In Java, you can throw exceptions manually using the throw keyword. This is useful when you want to enforce certain conditions in your code.

public class ThrowExceptionExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older.");
        }
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        }
    }
}

This code shows how to throw an exception:

  • public class ThrowExceptionExample { - Defines the main class.
  • public static void checkAge(int age) { - Declares a method to check age.
  • if (age < 18) { - Checks if age is less than 18.
  • throw new IllegalArgumentException(...); - Throws an IllegalArgumentException if the condition is met.
  • System.out.println("Access granted."); - Prints a message if the age is valid.
  • public static void main(String[] args) { - The main method where execution starts.
  • try { - Starts the try block.
  • checkAge(15); - Calls checkAge method with age 15, which throws an exception.
  • } catch (IllegalArgumentException e) { - Catches the IllegalArgumentException.
  • System.out.println(...); - Prints the exception message.
  • } - Closes the catch block and main method.

Custom Exception Handling

Creating custom exceptions allows developers to define specific error conditions tailored to their applications.

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validate(int value) throws CustomException {
        if (value < 0) {
            throw new CustomException("Negative value not allowed.");
        }
    }

    public static void main(String[] args) {
        try {
            validate(-10);
        } catch (CustomException e) {
            System.out.println("Caught a custom exception: " + e.getMessage());
        }
    }
}

This code demonstrates creating and using a custom exception:

  • class CustomException extends Exception { - Defines a custom exception class.
  • public CustomException(String message) { - Constructor that sets the exception message.
  • public static void validate(int value) throws CustomException { - Method to validate input.
  • if (value < 0) { - Checks if the value is negative.
  • throw new CustomException(...); - Throws the custom exception if the condition is met.
  • public static void main(String[] args) { - The main method where execution starts.
  • try { - Starts the try block.
  • validate(-10); - Calls validate method with a negative number, which throws a custom exception.
  • } catch (CustomException e) { - Catches the custom exception.
  • System.out.println(...); - Prints the exception message.
  • } - Closes the catch block and main method.

Best Practices and Common Mistakes

When working with exceptions in Java, consider the following best practices:

  • Use specific exceptions: Catch specific exceptions rather than using a generic catch block.
  • Don't ignore exceptions: Always handle exceptions appropriately; avoid empty catch blocks.
  • Document custom exceptions: Provide clear documentation for custom exceptions to help other developers understand their purpose.
  • Use try-with-resources: For resource management, use try-with-resources to ensure resources are closed properly.

Conclusion

In this blog post, we've explored the essential concepts of exception handling in Java, including checked and unchecked exceptions, throwing exceptions, and creating custom exceptions. Understanding and implementing effective exception handling techniques is crucial for developing resilient and user-friendly applications. Remember to follow best practices to avoid common mistakes and enhance your coding skills.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Understanding Hibernate ORM in Java: A Comprehensive Guide
Mar 16, 2026
Understanding JDBC Database Connectivity in Java: A Comprehensive Guide
Mar 16, 2026
Building RESTful APIs with Spring Boot: A Comprehensive Guide
Mar 16, 2026
Mastering File I/O in Java: A Comprehensive Guide to Reading and Writing Files
Mar 16, 2026
Previous in Java
Understanding Lambda Expressions in Java: A Comprehensive Guide
Next in Java
Mastering Multithreading in Java: A Comprehensive Guide
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,925 views
  • 2
    Error-An error occurred while processing your request in .… 11,259 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 216 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,449 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 150 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,488 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,217 views

On this page

🎯

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6280 views
  • Master Java Type Casting: A Complete Guide with Examples 6246 views
  • How to add (import) java.util.List; in eclipse 5844 views
  • org.openqa.selenium.SessionNotCreatedException: session not … 5776 views
  • java.lang.IllegalStateException: The driver executable does … 5116 views
View all Java posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor