- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Comprehensive Guide to Exception Handling in Java: Best Practices and Examples
Updated on 07 January, 2025
7.29K+ views
• 15 min read
Table of Contents
- What are Exceptions in Java and Their Significance? Understand with Examples
- How Java Facilitates Efficient Exception Handling and Essential Methods
- Designing and Implementing Custom Exceptions in Java
- Identifying and Understanding Common Java Exceptions
- Advanced Techniques for Exception Handling in Java
- Best Practices for Robust Exception Handling in Java
- How can upGrad Help You Advance Your Java Skills?
Did you know that Java powers over 9 million developers globally? Its reliability and scalability make it a favorite for everything from Android apps to complex financial systems. But what happens when things go wrong, like a file not found, invalid user input, or a network failure? That’s where exception handling in Java becomes crucial.
Exception handling allows you to anticipate, catch, and manage these errors, ensuring your application doesn’t crash and burn. Instead, it continues running smoothly, providing a better experience for users.
In this blog, you’ll learn how to master exception handling in Java with examples. From understanding the basics to implementing best practices, it will equip you with the tools to write resilient, error-tolerant code.
Let’s get started!
What are Exceptions in Java and Their Significance? Understand with Examples
In Java, exceptions are disruptions that occur during the program's execution, preventing it from proceeding normally. These runtime issues don’t have to spell disaster. Instead, Java provides a structured framework for detecting and managing these errors.
By handling exceptions, you can ensure smooth program flow, provide meaningful error messages to users, and safeguard against crashes.
Let’s explore exception handling in Java in more detail!
Understanding Exceptions in Java
Exceptions in Java are broadly categorized into two types: checked and unchecked exceptions. These categories help you determine which errors must be explicitly handled and which can occur without interrupting the program.
Have a look at the comparison table of both:
Aspect | Checked Exceptions | Unchecked Exceptions |
Definition | Exceptions checked at compile time. | Exceptions that occur at runtime. |
Examples | IOException, SQLException | ArithmeticException, NullPointerException |
Handling Requirement | Must be handled using try-catch or declared with throws. | No explicit handling required, but can be managed using try-catch. |
Occurrence | Often caused by external resources like files or databases. | Arises from logical errors in the code. |
To understand its implementation better, go through the examples given.
1. Checked Exception Example:
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
// Attempting to read a file that may not exist
FileReader file = new FileReader("nonexistentfile.txt");
} catch (IOException e) {
// Handling the IOException
System.out.println("Error: File not found!");
}
}
}
Output:
Error: File not found!
Code Explanation:
- The FileReader attempts to open a file that doesn’t exist, which triggers an IOException.
- The compiler forces you to handle the IOException because it’s a checked exception.
2. Unchecked Exception Example:
public class UncheckedExceptionExample {
public static void main(String[] args) {
// Attempting to divide by zero
int result = 10 / 0; // Triggers ArithmeticException
System.out.println("Result: " + result);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Code Explanation:
- Dividing by zero triggers an ArithmeticException at runtime.
- Unlike checked exceptions, the compiler doesn’t enforce this error but should be addressed logically to prevent program failure.
Hierarchy of Exceptions in Java
Java’s exception system follows a clear hierarchy that starts with the Throwable class. This class has two main subclasses: Error and Exception. This structure helps you understand how to categorize and manage different types of errors.
Here’s an overview of the hierarchy of Java expectation classes:
- Throwable: The root of all exceptions and errors in Java.
- Error: Represents severe issues beyond the application’s control (e.g., OutOfMemoryError, StackOverflowError).
- Exception: Represents application-level issues that can be caught and handled.
Have a look at a code example demonstrating the hierarchy:
public class ExceptionHierarchyExample {
public static void main(String[] args) {
try {
// Attempting to access a null object
String str = null;
System.out.println(str.length()); // Triggers NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException!");
} catch (Exception e) {
System.out.println("Caught a general Exception!");
}
}
}
Output:
Caught a NullPointerException!
Explanation:
- Accessing a null object triggers a NullPointerException, a RuntimeException subclass.
- The exception is caught by the specific NullPointerException block first. It would fall back to the general Exception block if not handled there.
By understanding these fundamental concepts of exception handling in Java, you can write resilient, error-free applications.
If you wish to upskill and enhance these in-demand tech concepts, explore upGrad’s comprehensive software development programs from top universities!
Now, in any robust application, errors are inevitable — but how you handle them makes all the difference. Let’s see how you do it!
How Java Facilitates Efficient Exception Handling and Essential Methods
Java, one of the most developer-friendly languages, offers a structured exception-handling framework to tackle errors efficiently without disrupting the program flow. It ensures you’re not just catching errors but managing them intelligently.
Exception handling in Java includes key constructs like try-catch, finally, throw, and throws, which enable developers to handle errors effectively, combined with robust APIs and tools.
Let’s explore how these mechanisms work and how they prevent abrupt program failures.
1. try-catch: Controlled Error Resolution
- The try block contains code that might throw an exception.
- The catch block handles specific exceptions, allowing you to define a response.
Code Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Triggers ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
}
}
Output:
Error: Cannot divide by zero!
In this code example of try-catch in Java, the program gracefully handles the exception instead of crashing and continues.
2. finally: Ensuring Cleanup
The finally block is always executed, regardless of whether an exception occurs, making it ideal for cleanup operations like closing files or releasing resources.
Code Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2};
System.out.println(numbers[5]); // Triggers ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds!");
} finally {
System.out.println("Execution complete.");
}
}
}
Output:
Error: Index out of bounds!
Execution complete.
In this example, the ‘finally’ block ensures that critical tasks are completed, even if an exception occurs.
3. throw: Manually Raising Exceptions
- The throw keyword is used explicitly to raise an exception in the program.
- It is typically used when a specific condition in your code requires you to generate an error manually.
Code Example:
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or older.
In the code snippet, when the condition age < 18 is met, the program raises an IllegalArgumentException.
4. throws: Declaring Exceptions
The throws keyword is used to declare the exceptions a method might throw, allowing the caller of the method to handle them.
Code Example:
public class ThrowsExample {
public static void checkNumber(int number) throws Exception {
if (number < 0) {
throw new Exception("Negative number not allowed!");
}
}
public static void main(String[] args) {
try {
checkNumber(-5);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: Negative number not allowed!
Here, the throws keyword informs the caller that checkNumber might throw an exception, which must be handled explicitly in the calling method.
This structured way of exception handling in Java prevents programs from abruptly stopping by:
- Isolating Errors: Code prone to errors is isolated within try blocks, ensuring the rest of the program is unaffected.
- Providing Recovery Paths: The catch block offers a way to handle errors, recover gracefully, or provide alternative logic.
- Cleanup with finally: Resources like file handles or network connections are properly closed, preventing resource leaks.
Also Read: File Handling in Java: How to Work with Java Files?
While Java’s built-in exceptions cover many standard error scenarios, some applications require custom error messages or specific behavior.
This is where custom exceptions come in. Let’s dive into it!
Designing and Implementing Custom Exceptions in Java
A custom exception allows you to create meaningful, application-specific error handling. For example, if you’re building a banking application, you might want to create exceptions like InsufficientFundsException or AccountNotFoundException to represent domain-specific errors.
Custom exceptions are useful when:
- The built-in exceptions don’t clearly convey the problem in your application’s context.
- You must add extra information or logic to the error, such as user-friendly messages or custom behavior.
- You want to improve code readability and make debugging easier.
Now, let’s see how to create the custom exception step-by-step:
Step 1. Decide the Type of Custom Exception:
- Extend the Exception class if you want your exception to be a checked exception (requires explicit handling).
- Extend the RuntimeException class if you want it to be an unchecked exception (it can occur without explicit handling).
Step 2. Define the Exception Class:
Add constructors to initialize the exception with custom messages or additional data.
Step 3. Throw and Handle the Custom Exception:
- Use the throw keyword to raise the exception.
- Use try-catch blocks or throws declarations to handle it appropriately.
Code Example: Creating a Custom Exception
Now that you have got the theoretical steps, let’s see the complete process implementation with code examples to help you understand better.
1. Define the Custom Exception Class
// Defining a custom exception
class InsufficientFundsException extends Exception {
// Constructor with a custom message
public InsufficientFundsException(String message) {
super(message); // Pass the message to the Exception class
}
}
2. Use the Custom Exception
public class CustomExceptionExample {
// Method to simulate withdrawing money
public static void withdraw(double amount, double balance) throws InsufficientFundsException {
if (amount > balance) {
// Throw the custom exception if funds are insufficient
throw new InsufficientFundsException("Insufficient funds: Unable to withdraw " + amount);
}
System.out.println("Withdrawal successful! Remaining balance: " + (balance - amount));
}
public static void main(String[] args) {
double balance = 500.0; // Initial account balance
try {
withdraw(600.0, balance); // Attempt to withdraw more than the balance
} catch (InsufficientFundsException e) {
// Handle the custom exception
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: Insufficient funds: Unable to withdraw 600.0
In the above code snippet:
- A constructor is provided to accept a custom error message, which is passed to the parent Exception class.
- The withdraw method checks if the withdrawal amount exceeds the balance. If true, it throws the InsufficientFundsException.
- In the main method, a try-catch block handles the exception.
Wish to build your foundational knowledge of Java? Start with upGrad’s core Java basics course and explore further!
Also Read: How to Code, Compile, and Run Java Projects
Exceptions are an integral part of programming, and as a Java developer, you’ll encounter various of them. Let’s understand them!
Identifying and Understanding Common Java Exceptions
Understanding the most common exceptions and their causes is essential for debugging effectively and writing error-resilient code.
Let’s explore some of the frequently encountered exceptions in Java, their causes, and how they occur in everyday coding.
1. NullPointerException: Accessing Null References
This exception occurs when you attempt to access or modify an object that has not been initialized (i.e., is null).
How It Happens:
- Calling a method on a null object.
- Accessing a null object’s properties.
Code Example:
public class NullPointerExample {
public static void main(String[] args) {
String text = null; // Uninitialized string
System.out.println(text.length()); // Triggers NullPointerException
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
How to Avoid: Always check for null before accessing objects, as shown in the below code:
if (text != null) {
System.out.println(text.length());
}
2. IOException: Input/Output Operation Failures
If something goes wrong, this exception is thrown during I/O operations, such as reading from or writing to a file.
How It Happens:
- File not found.
- Insufficient permissions to access the file.
Code Example:
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistentfile.txt"); // File not found
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: nonexistentfile.txt (No such file or directory)
How to Avoid:
- Verify file paths and permissions before performing file operations.
- Use exception handling (try-catch) to handle potential errors gracefully.
3. ArithmeticException: Invalid Arithmetic Operations
This exception is triggered by invalid arithmetic operations, such as dividing a number by zero.
How It Happens:
- Performing a division by zero.
- Using invalid mathematical expressions.
Code Example:
public class ArithmeticExample {
public static void main(String[] args) {
int result = 10 / 0; // Division by zero
System.out.println("Result: " + result);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
How to Avoid: Check denominators before performing division. See how it’s done below:
if (denominator != 0) {
System.out.println(10 / denominator);
} else {
System.out.println("Cannot divide by zero.");
}
Understanding these exceptions is the first step toward mastering exception handling in Java with examples!
Also Read: Top 32 Exception Handling Interview Questions and Answers [For Freshers & Experienced]
Next, let’s get into some advanced techniques for exception handling in Java with examples!
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Advanced Techniques for Exception Handling in Java
Exception handling in Java goes beyond basic try-catch blocks. Advanced techniques enable developers to write cleaner, more efficient, context-aware, error-handling code.
Let’s explore these advanced concepts of exception handling in Java with examples.
1. Exception Propagation
Exception propagation is a mechanism in Java where an exception raised in one method moves up the call stack until a try-catch block catches it or terminates the program if unhandled.
When an exception occurs:
- The method where it’s thrown doesn’t handle it.
- It is passed (propagated) to the method that called it.
- This continues up the stack until it’s caught or the program terminates.
Have a look at the code example below:
public class ExceptionPropagationExample {
// Method that throws an exception
public static void methodA() {
throw new ArithmeticException("Division by zero in methodA");
}
// Method that calls methodA
public static void methodB() {
methodA(); // Exception propagates to methodB
}
public static void main(String[] args) {
try {
methodB(); // Exception propagates to main
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Output:
Caught Exception: Division by zero in methodA
Code Explanation:
- methodA: Throws an ArithmeticException.
- methodB: Does not handle the exception, so it propagates to main().
- main(): Catches the exception and prints the message.
This shows how exceptions travel up the call stack, allowing centralized error handling.
2. Chained Exceptions
Sometimes, one exception causes another. Chaining exceptions lets you link these related errors, preserving the full context for debugging.
This is particularly useful when you want to:
- Preserve the original exception.
- Add additional context to the error message.
Have a look at the code example below:
public class ChainedExceptionExample {
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Caused by: " + e.getCause());
}
}
// Method that simulates an error and chains it
public static void methodA() throws Exception {
try {
int result = 10 / 0; // Triggers ArithmeticException
} catch (ArithmeticException e) {
throw new Exception("Error in methodA", e); // Chaining exception
}
}
}
Output:
Caught Exception: Error in methodA
Caused by: java.lang.ArithmeticException: / by zero
Code Explanation:
- The ArithmeticException is caught in methodA and wrapped in a new Exception using chaining.
- In main(), both the original and chained exceptions are accessible for debugging, preserving the context.
3. Using try-with-resources (Java 7 and Above)
Managing resources like file streams or database connections can be tricky. If not closed properly, they can lead to resource leaks.
The try-with-resources statement, introduced in Java 7, automates resource management by automatically closing resources when no longer needed.
Have a look at the code example below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
// Using try-with-resources for automatic resource management
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print file content
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
Output (if file exists):
File content line 1
File content line 2
...
Output (if file doesn’t exist):
Error reading the file: example.txt (No such file or directory)
Code Explanation:
- Automatic Resource Management: The BufferedReader resource is automatically closed after the try block, even if an exception occurs.
- Simplified Code: No need for explicit finally blocks to close resources manually.
There you go! You must practice these concepts to take your exception handling in Java skills to the next level!
Also Read: Top 10 Java Books to Read to Improve Your Knowledge
Best Practices for Robust Exception Handling in Java
Exception handling in Java is not just about catching errors; it’s about doing so in a way that ensures your application remains reliable, maintainable, and efficient. Following best practices helps you write clean and predictable code that is easier to debug.
Let’s explore key practices to make your exception handling robust and effective.
1. Catch Specific Exceptions
Always catch specific exceptions instead of using generic ones like Exception or Throwable. Specific handlers make debugging easier and provide clearer error messages.
Understand it with the code snippet below:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: Division by zero.");
}
2. Log Exceptions with Meaningful Messages
Use proper logging frameworks (e.g., Log4j, SLF4J) to log exceptions. Include meaningful messages and stack traces to provide a clear context for debugging.
See how it should be implemented:
import java.util.logging.Logger;
public class LoggingExample {
private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
logger.severe("Arithmetic error occurred: " + e.getMessage());
}
}
}
3. Avoid Using Exceptions for Control Flow
Exceptions are expensive in performance and should not replace regular conditional checks. Use proper logic to handle predictable conditions instead of relying on exceptions.
Example (What NOT to Do):
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Avoid triggering exceptions deliberately
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!"); // Poor control flow
}
Better Approach:
int[] numbers = {1, 2, 3};
if (5 < numbers.length) {
System.out.println(numbers[5]);
} else {
System.out.println("Index out of bounds!");
}
4. Use try-with-resources for Efficient Resource Management
Always use try-with-resources to manage resources like file streams and database connections. It ensures resources are closed automatically, even in the event of an exception.
Here’s how to do it:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesBestPractice {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
Adopting these best practices will make your applications more resilient and maintainable, helping you become a better Java developer.
Also Read: Java Developer Salary: What to Expect in India 2025
How can upGrad Help You Advance Your Java Skills?
Do you want to level up your Java skills and confidently tackle real-world programming challenges? Mastering core concepts like exception handling in Java is a game-changer for developers aiming to build robust, error-free applications.
upGrad specializes in bridging the gap between learning and career advancement. Their Java programs are tailored to equip you with foundational and advanced skills, ensuring you’re ready to tackle industry challenges head-on.
Some of the top courses include:
- Java Object-oriented Programming
- JavaScript Basics from Scratch
- Advanced JavaScript for All
- Web Analytics Course for Beginners
Take the first step today: book a career counseling session with upGrad experts, upskill, and excel in your future ahead!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Explore our Popular Software Engineering Courses
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
In-Demand Software Development Skills
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Read our Popular Articles related to Software
References:
https://www.cogentinfo.com/resources/java-developer-demographics-and-statistics-in-the-us
Frequently Asked Questions
1. What is exception handling in Java?
It’s a mechanism to detect and handle runtime errors, ensuring smooth program execution.
2. Why is exception handling important in Java?
It prevents abrupt program termination and helps manage errors gracefully, improving reliability.
3. What are checked and unchecked exceptions?
Checked exceptions are enforced by the compiler (e.g., IOException), while unchecked exceptions occur at runtime (e.g., NullPointerException).
4. What is exception propagation?
It refers to how exceptions move up the call stack until they’re caught or cause program termination.
5. What is the purpose of custom exceptions in Java?
Custom exceptions help define application-specific errors with meaningful context.
6. How does try-with-resources work?
It ensures the automatic closure of resources like file streams after use, preventing resource leaks.
7. What is a NullPointerException?
This occurs when you try to access or modify a null object reference.
8. What is exception chaining?
It links multiple exceptions to preserve context, providing more details about the root cause.
9. Why should exceptions not be used for control flow?
Using exceptions for control flow reduces performance and makes code harder to maintain.
10. How can exceptions be logged effectively?
Use frameworks like Log4j or SLF4J to log exceptions with meaningful messages and stack traces.
11. How can upGrad help me learn Java exception handling?
upGrad offers programs like Advanced Certificate in Java Programming, featuring in-depth modules on exception handling and practical projects.
RELATED PROGRAMS