CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Exception Handling in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

Exception Handling in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

Exception handling in Java is a critical mechanism that allows developers to manage runtime errors gracefully, ensuring robust and fault-tolerant applications. By anticipating and addressing unexpected events, such as invalid input or resource unavailability, Java programs can maintain stability and provide meaningful feedback. This guide explores Java exception handling in depth, covering types, syntax, best practices, and common pitfalls.

Table of Contents

  • What is Exception in Java?
  • Java Exception Hierarchy
  • Keywords for Exception Handling
  • Exception Handling Mechanisms
    • 1. try-catch Block
    • 2. Multiple catch Blocks
    • 3. finally Block
    • 4. try-with-resources (Java 7+)
    • 5. throw and throws
  • Best Practices for Effective Exception Handling
  • Common Mistakes to Avoid
  • Creating Custom Exceptions
  • Conclusion
  • FAQs
    • What is the purpose of the finally block?
    • When to use checked vs unchecked exceptions?
    • Can I have multiple catch blocks?
    • What’s the difference between throw and throws?

What is Exception in Java?

An exception is an event disrupting the normal flow of a program. Java categorizes exceptions into three types:

  1. Checked Exceptions: Compile-time enforced (e.g., IOException).
  2. Unchecked Exceptions: Runtime errors (e.g., NullPointerException).
  3. Errors: Severe system-level issues (e.g., OutOfMemoryError).

Java Exception Hierarchy

Java’s exception classes inherit from the Throwable class:

  • Throwable
    • Error (e.g., StackOverflowError)
    • Exception
      • Checked Exceptions (e.g., SQLException)
      • RuntimeException (Unchecked, e.g., ArrayIndexOutOfBoundsException)

Keywords for Exception Handling

Java provides five core keywords:

  1. try: Encloses code that might throw exceptions.
  2. catch: Handles specific exceptions.
  3. finally: Executes code regardless of exceptions.
  4. throw: Manually throws an exception.
  5. throws: Declares exceptions a method might throw.

Exception Handling Mechanisms

1. try-catch Block

try {  
  // Risky code  
} catch (IOException e) {  
  System.out.println("Error: " + e.getMessage());  
}  

2. Multiple catch Blocks

Handle different exceptions separately:

try {  
  // Code  
} catch (FileNotFoundException e) {  
  // Handle file not found  
} catch (IOException e) {  
  // General IO error  
}  

3. finally Block

Ideal for cleanup tasks (e.g., closing files):

try {  
  // Open file  
} catch (IOException e) {  
  // Handle error  
} finally {  
  // Close file  
}  

4. try-with-resources (Java 7+)

Automatically closes resources like streams:

try (FileReader fr = new FileReader("file.txt")) {  
  // Use resource  
} catch (IOException e) {  
  // Handle error  
}  

5. throw and throws

  • throw: Trigger a custom exception:
throw new IllegalArgumentException("Invalid input");  
  • throws: Declare exceptions in method signatures:
public void readFile() throws IOException { ... }  

Best Practices for Effective Exception Handling

  • Avoid Swallowing Exceptions: Never leave catch blocks empty.
  • Use Specific Exceptions: Catch narrower exceptions before broader ones.
  • Log Exceptions: Use logging frameworks like Log4j.
  • Close Resources Properly: Leverage try-with-resources.
  • Custom Exceptions: Extend Exception or RuntimeException for app-specific errors.

Common Mistakes to Avoid

  • Catching Throwable or Error unnecessarily.
  • Using broad catch (Exception e) blocks.
  • Ignoring exceptions, leading to hidden bugs.
  • Failing to close resources, causing memory leaks.

Creating Custom Exceptions

Extend Exception for checked exceptions:

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

Or extend RuntimeException for unchecked:

public class InvalidUserException extends RuntimeException { ... }  

Conclusion

Mastering exception handling in Java is essential for building resilient applications. By understanding types, keywords, and best practices, developers can write cleaner, more maintainable code. Always prioritize meaningful error logging and resource management to enhance user experience and debug efficiency.

FAQs

What is the purpose of the finally block?

Ensures critical code (e.g., resource cleanup) runs even if an exception occurs.

When to use checked vs unchecked exceptions?

Use checked for recoverable errors (e.g., file not found) and unchecked for programming errors (e.g., null pointers).

Can I have multiple catch blocks?

Yes, but order them from specific to general.

What’s the difference between throw and throws?

throw triggers an exception, while throws declares it in a method signature.

Related Posts:

  • Exception Handling Keywords in Java
  • What is Try-With-Resources in Java? A Complete Guide
  • Control Statements in Java
  • Top 10 Common Java Errors
  • Suppressed Exceptions in Java
  • Identifiers in Java
Tags:javalanguage-fundamentals
Was this article helpful?
← Previous ArticleJDBC Best Practices: Writing Robust and Efficient Database Code
Next Article →Bitwise and Shift Operator in Java

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap