Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Understanding Exception Hierarchy in Java Explained

Updated on 05 July, 2024

17.87K+ views
9 min read

The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the execution of a program and disrupts the program’s normal flow. Exceptions are unwanted and mostly unexpected, generally arising at run- or compile-time. These Exceptions must be handled to ensure the program runs in its natural flow. However, it would help to know what kinds of Exceptions are present with Java before we handle Exceptions. Through this article, I will explain various types of Exceptions in Java and the Exception Hierarchy in java. 

Check out our free courses to get an edge over the competition.

Exceptions Hierarchy in Java 

The hierarchy of Exceptions in the Java programming language begins with the Throwable class – which comes from the Object class and is its direct subclasswhileThe Exception class presents all This Throwable class further branches into two subclasses – Error and Exception. Here’s a flowchart to understand the Java Exception hierarchy better: 

The Exception class presents all the Exceptions that you might need to handle while working with the Java programming language. Some commonly known and encountered examples of such Exceptions include NullPointerException, ClassNotFoundException, IllegalArgumentException, etc. 

On the other hand, the Error class takes care of more severe problems in your Java program architecture and is not taken care of within the application code. Exception hierarchy in java with examples of errors are InternalError, AssertionError, OutOfMemoryError, etc. 

Check out upGrad’s Advanced Certification in Cyber Security

Java has two main types of exceptions:

  • Checked Exceptions – These are also known as compile-time exceptions. 
  • Unchecked Exceptions – These are also known as runtime exceptions. 

One important point to note at this juncture is that unchecked Exceptions are all subclasses of the RuntimeException class. We will talk more about checked and unchecked exceptions later on in this article. But before that, let’s look at essentially how Errors and Exceptions differ in their working so that there is no confusion. 

Reasons why Exceptions do occur? 

Consider exceptions as the unexpected guests at the party of your program’s execution — they show up uninvited due to a few common hiccups. Here’s why they might knock on your door: 

  • Human Error: Sometimes, it’s just us. Maybe we mistype something or expect a file to be in one place when it’s in another. It happens to the best of us.
  • Resource Issues: Programs also throw a fit when they can’t find what they need, like trying to read a file that’s gone missing or reaching out to a database that’s taking a nap.
  • Environmental Mishaps: Occasionally, the environment where the program runs decides to act up — think of a network glitch right in the middle of a data transfer.  
  • Bugs in the Code: And then, there are those pesky bugs. A slip in the logic or using a method incorrectly can easily ruffle the feathers of your otherwise smooth-running code.
  • System Overload: Even systems have bad days; maybe there’s not enough memory to carry out your commands.

In Java, these scenarios are neatly packed into ‘exceptions’ so you can manage them gracefully, rather than letting your program crash. It’s Java’s saying, “Heads up, something’s not right, but you can handle it!” 

Errors and Exceptions in Java – How Do They Differ?

The official documentation of the Java programming language refers to Errors as occurrences during your Java programming that – “indicate serious problems that a reasonable application should not try to catch.” The seriousness of Errors is clear from the way this statement is poised. Clearly, this refers to the set of problems that your program might face that is not possible for it to recover from without either refactoring the code or modifying the Java application architecture.

Check out upGrad’s Advanced Certification in Blockchain 

Let’s look at a Java method that is going to throw an error: 

public static void print(String S) {

    print(S);

}

In the code mentioned above, the method print() acts as a recursive method that keeps calling itself repeatedly, over and over again, until it reaches the maximum allowed size for a thread stack in Java. At that point, it exits execution with a very common – StackOverflowError, which reads something like: 

Exception in thread “main” java.lang.StackOverflowError

at StackOverflowErrorExample.print(StackOverflowErrorExample.java:3)

As the above example shows, the method throws an example, but this error cannot be handled in the code itself. So, the program simply quits execution because the damage is irrecoverable. As a solution, the code needs to be modified. 

Contrary to Errors, Exceptions indicate conditions that can be caught by a reasonable application. Exceptions in Java include issues that might occur either at the compile-time or during run time. These Exceptions happen rather frequently in all applications – especially during the testing and debugging phase. As a result, Exceptions in Java can be handled within the program itself to ensure that the code runs its natural flow. 

Now, let’s talk a bit more about Exception Hierarchy in Java by looking at what checked and unchecked Exceptions are. 

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Checked and Unchecked Exceptions in Java

As mentioned earlier, Exceptions in a Java program can happen either during the compile-time or during the run time. This is what gives us the two broad types of Exceptions present in Java. Here’s looking at these two exceptions in detail. 

Compile-time Exceptions

Exceptions that happen at the compile time are known as compile-time exceptions. These are also called checked exceptions because of the fact that you need to explicitly check them in your Java program and handle them in the code itself. Classes like InterruptedException, IOException, and more are checked exceptions. 

Let’s look at a method that can handle a checked exception: 

public void writeAFile() {

try (BufferedWriter b_w = new BufferedWriter(new FileWriter("myFile.txt"))) {

        b_w.write("Testing");

    } catch (IOException ioe) {

        ioe.printStackTrace();

    }

}

As you can see, there are two statements in the above code’s try block – 

  • Instantiating the object – BufferedWriter
  • Using the object to write to the file

Both these statements can throw IOException. IOException, being a Checked Exception, needs to be handled either by the caller or the method. In the above example, you can see the exception being handled within the method itself.

Runtime Exceptions

Contrary to compile-time exceptions that are thrown during compile time, runtime or unchecked exceptions can be thrown “at any time”, which essentially means at runtime. As a result of this, methods don’t need to explicitly use catch-and-throw blocks to handle these unchecked exceptions. Some of the classes that inherit unchecked runtime exceptions include – NullPointerException, ArithmeticException, etc. 

Let’s look at a piece of Java code that throws a NullPointerException unchecked Exception and that is not handled in the piece of code unlike earlier. Here it is: 

public void writeToFile() {

try (BufferedWriter b_w = null) {

        b_w.write("Test");

    } catch (IOException ioe) {

        ioe.printStackTrace();

    }

}

When you call the above method, the program will throw a NullPointerException since the BufferedWriter object is null. Here is what the exception would read like: 

Exception in thread “main” java.lang.NullPointerException

    at IOExceptionExample.writeToFile(IOExceptionExample.java:10)

    at IOExceptionExample.main(IOExceptionExample.java:17)

When to use Checked & Unchecked Exceptions

In the Java universe, exceptions are like the plot twists of a story — some are anticipated, and some catch you off-guard. Understanding when to use checked and unchecked exceptions is akin to knowing when to bring an umbrella or when to brace for an unexpected downpour. Checked exceptions are gentle reminders that something might go awry, prompting you to handle them carefully. Unchecked exceptions, on the other hand, are the unforeseen glitches that usually point to a bug in your code. 

In this section, we’ll unravel this concept further, aided by a sequence diagram that maps out the decision-making process, ensuring that every Java developer knows precisely which type of ‘umbrella’ to use in the face of Java’s exception ‘weather.’ Let’s prepare for all conditions — predictable or not. 

Explanation of the above Sequence Diagram:

  • The Developer starts by implementing a feature within the Java Application. 
  • The application checks at compile time if a Checked Exception is needed, which should be used when an exception is recoverable and expected. 
  • If a checked exception is appropriate, the Developer is prompted to handle or declare it, ensuring that the application remains robust and user-friendly. 
  • For Unchecked Exceptions, which occur at runtime, the diagram shows that these are typically due to programming errors and do not require explicit handling by the Developer. 
  • Instead, unchecked exceptions are used for issues that the application cannot recover from and often indicate bugs that need to be addressed in the code. 

When writing Java code, it’s vital to distinguish between situations that call for checked exceptions and those that are best served by unchecked exceptions. Checked exceptions are a direct communication channel, prompting the caller to proactively handle potential issues. Unchecked exceptions, conversely, signal to the Developer that there’s an underlying issue that needs correction. This distinction not only aids in writing clear and effective code but also fosters a more intuitive and error-resilient application. 

Conclusion

With that, we come to the end of this blog on understanding the Exception Hierarchy in Java. Please keep in mind that this is by no means comprehensive coverage of Exceptions in Java and how to handle them. For that, I believe you should dig deeper and expose yourself to different possible Exceptions to see how they work. Knowing Exception Handling will set you up for a successful career as a full-stack developer since Exceptions form the basics of any application. 

Types of exception handling in Java include: Try-Catch for handling exceptions, Finally for post-execution code, Throw to explicitly raise exceptions, and Throws to declare potential exceptions in a method.

I strongly recommend you explore specialized full stack development course offered by upGrad – Executive PG Programme in Software Development – Specialisation in Full Stack Development – where you go through all the nuances of software development by focusing majorly on Full Stack development. We suggest you check out the course and probably book a seat soon! 

Frequently Asked Questions (FAQs)

1. Which class is present at the top of the Exception Hierarchy in Java?

The Throwable class is at the top of the Exception Hierarchy in Java.

2. What are the different kinds of Exceptions present in Java?

Java has unchecked as well as checked exceptions. Checked Exceptions are also called compile-time exceptions, whereas Unchecked Exceptions are also known as runtime exceptions.

3. How are exceptions handled in Java?

The try-catch is the easiest way to handle Exceptions in Java. The main piece of code that you want to be run needs to be put in the try block, while one or more catch blocks will catch all the exceptions that the code throws. This method will detect any type of Java exceptions that get thrown.

4. What is the exception order in java?

In Java, the exception order is: 'Error', 'RuntimeException' (unchecked exceptions), and other 'Exception' classes (checked exceptions), forming a hierarchy where each can be caught or thrown as per the level of granularity needed.

RELATED PROGRAMS