Types of Exceptions in Java – Explanation with Examples 2024

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

An exception in Java is nothing but an unpredicted condition. Different types of exceptions in Java can occur while executing a code. It can be a bug or error in the code and stop the flow of the program. You will come across multiple ways to handle the different types of exceptions in Java to prevent code termination. Dive into this article to learn more about the different types of exceptions in Java. 

 

Exception Class Hierarchy in Java

The exception class hierarchy in Java can be defined as the following:

  1. java.lang Object
  2. Throwable
  3. Exception 
    • Unchecked Exceptions
    • Checked Exceptions
  4. Error

Enroll: Full Stack Development course

Types of Exceptions in Java

The different types of exceptions in Java serve different purposes. Learn about them below:

Built-in Exceptions

These types of exceptions in Java are predefined within Java libraries. These types of exceptions in Java occur most frequently. You can consider an Arithmetic Exception in this category. This predefined exception is found in the Java.lang.package. These exceptions can be divided into the following categories. 

Checked Exceptions

These types of exceptions in Java are called compile-time exceptions. These exceptions are checked by the compiler while the compilation process is ongoing. These types of exceptions in Java can confirm whether a programmer is handling a specific exception. 

Examples of Checked Exceptions

The syntax for this type of exception in Java is as follows:

va.io.*; class demo1 { public static void main(String args[]) { FileInputStream input1 = null; /* FileInputStream(File filename) is a constructor that will throw * FileNotFoundException (a checked exception) */ input1 = new FileInputStream("D:/file.txt"); int m; // The read() of FileInputStream will also throw a checked exception while(( m = input1.read() ) != -1) { System.out.print((char)m); } // The close() will close the file input stream, and it will also throw an exception input1.close(); } }

Learn about Java Operators

List of Common Checked Exceptions in Java

  • SQLException: It occurs due to the failure of a database operation.
  • IOException: It occurs due to the failure of an input/output operation.
  • ClassNotFoundException: It occurs when a specific class cannot be identified.
  • NoSuchMethodExceptionL occurs when a specific method cannot be identified.
  • InstantiationException: It occurs when a specific object cannot be instantiated.  

Unchecked Exceptions

These types of exceptions in Java occur during program execution. Therefore, these types of exceptions are also called runtime exceptions. The unchecked exceptions are not given any attention during the compilation process. 

Examples of Unchecked Exceptions

The syntax for this type of exception in Java is as follows:
Types of Exceptions in Java - Explanation with Examples 2023

va.util.Scanner; public class Sample_RunTimeException { public static void main(String[] args) { // Reading user input Scanner input_dev = new Scanner(System.in); System.out.print("Enter your age in Numbers: "); int age1 = input_dev.nextInt(); if (age1>20) { System.out.println("You can view the page"); } else { System.out.println("You cannot view the page"); } } }

Read: OOPS Concept in Java

List of Common Unchecked Exceptions in Java
  • RuntimeException: It is the superclass of different unchecked exceptions.
  • Arithmetic Exception: It occurs due to the failure of an arithmetic operation.
  • NullPointer Exception: It occurs when a null value is applied in place of an object.
  • ConcurrentModification Exception: It occurs when a collection is modified during its iteration.
  • IllegalState Exception: It occurs due to the detection of an illegal state.
  • IllegalArgument Exception: It occurs while using an illegal argument.
  • ArrayIndexOutofBounds Exception: It occurs in the case of an out-of-bound array index. 

Errors

The ERROR class refers to serious problems causing a program to abort. The different types of errors in Java are as follows:

  • OutofMemoryError: It courts when the JVM memory is over.
  • VirtualMachineError: It is the superclass of different errors occurring in the JVM.
  • StackOverflowError: It occurs due to stack overflow.
  • NoClassDefFoundErrorL It occurs when a class cannot be identified.
  • AssertionError: It occurs due to the failure of an assertion.
  • ExceptionInInitializerError: It occurs due to an exception in the static initializer of a class.
  • LinkageError: It occurs due to linkage problems.

Explore: Types of Inheritance in Java 

User-defined Exception

At times, the built-in types of exceptions in Java cannot explain a particular situation. In that case, the user can create user-defined exceptions. This type of exception can enable a programmer to tackle the edge cases for debugging a program. 

Example and Syntax for User-Defined Exceptions

The syntax for this type of exception in Java is as follows:

va.util.*; class UserDefinedException{ public static void main(String args[]){ try{ throw new NewException(5); } catch(NewException ex){ System.out.println(ex) ; } } } class NewException extends Exception{ int x; NewException(int y) { x=y; } public String toString(){ return ("Exception value = "+x) ; } }

Understand: What is Inheritance in Java – A Complete Guide

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Difference Between Types of Exception in Java: Checked and Unchecked Exception 

Checked Expectation Unchecked Expectation
This type of exception in Java is checked and handled at compile time. This type of exception in Java is not checked and handled at compile time.
They are direct subclasses but not extended from RuntimeException class. This is a direct subclass of the RuntimeException class.
They occur when the probability of failure is high. They occur due to programming errors.
Some common checked exceptions include DataAccessException, iOException, and InterruptedException. Some common unchecked exceptions include InvalidClassException, ArithmeticException, and NullPointerException.
They are propagated with the help of the throws keyword. They propagate automatically.

 

Importance of Proper Exception Handling

Handling the right types of exceptions in Java can help you recover from errors. Therefore, your program will become stronger and more resistant to unexpected conditions. By detecting and tackling the types of exceptions, your program will be able to deliver a more stable user experience. 

Understand: What is Inheritance in Java – A Complete Guide

Types of Exceptions in Java - Explanation with Examples 2023

Best Practices for Exception Handling

Some of the best practices for handling different types of exceptions are as follows:

  1. Clean up resources in a final block or opt for the try-with-resource statement.
  2. Always throw in specific types of exceptions in Java.
  3. While specifying a Java exception, you need to document it inside the Javadoc. 

Read: Fibonacci series in C

Conclusion

The different types of exceptions in Java prevent the further execution of a code. You will come across built-in and user-defined exceptions in Java. Built-in exceptions can be checked or unchecked. Meanwhile, the user-defined types of exception can allow programmers to debug programs easily.

FAQs
Some challenges while handling different types of exceptions involve unspecific exceptions. Another challenge is logging and throwing this type of exception in Java.
Some of the best practices for handling different types of exceptions in Java include cleaning up resources in a Finally Block or preferring specific exceptions.
The major types of exceptions in Java include built-in and user-defined exceptions.
You can create custom types of exceptions in Java with the help of user-defined classes.

Book a free counselling session

India_flag

Get a personalized career roadmap

Get tailored program recommendations

Explore industry trends and job opportunities

left dot patternright dot pattern

Programs tailored for your Success

Popular

Data Science

Technology

Finance

Management

Future Tech

Upskill with expert articles
View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved