Exception tree in java

Java Exceptions Hierarchy Explained

Java Exceptions Hierarchy Explained

In Java “an event that occurs during the execution of a program that disrupts the normal flow of instructions” is called an exception. This is generally an unexpected or unwanted event which can occur either at compile-time or run-time in application code. Java exceptions can be of several types and all exception types are organized in a fundamental hierarchy.

Java Exceptions Hierarchy

The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses — Exception and Error.

The diagram below shows the standard exception and error classes defined in Java, organized in the Java exceptions hierarchy:

java-exceptions-hierarchy-example

Figure 1: Exceptions hierarchy in Java

The Exception class is used for exception conditions that the application may need to handle. Examples of exceptions include IllegalArgumentException , ClassNotFoundException and NullPointerException .

The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code. Examples of errors include InternalError , OutOfMemoryError and AssertionError .

Exceptions are further subdivided into checked (compile-time) and unchecked (run-time) exceptions. All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses of Exception besides RuntimeException are checked exceptions.

Java Errors vs Exceptions

According to the official documentation, an error “indicates serious problems that a reasonable application should not try to catch.” This refers to problems that the application can not recover from — they should be dealt with by modifying application architecture or by refactoring code.

Here is an example of a method that throws a error, which is not handled in code:

public static void print(String myString)

In this example, the recursive method “print” calls itself over and over again until it reaches the maximum size of the Java thread stack, at which point it exits with a StackOverflowError :

Exception in thread "main" java.lang.StackOverflowError at StackOverflowErrorExample.print(StackOverflowErrorExample.java:6)

As seen above, the method throws the error during execution but does not handle it in code — the program simply exits when the error occurs since it is irrecoverable and requires a change in the code itself.

Exceptions, on the other hand, indicate “conditions that a reasonable application might want to catch.” These could include problems that can occur at compile-time (checked exceptions) or run-time (unchecked exceptions) and can happen rather frequently in most applications — especially during development. Checked exceptions should be handled in application code, whereas unchecked exceptions don’t need to be handled explicitly.

Читайте также:  Html form this page

Checked vs Unchecked Exceptions

Checked Exceptions

Exceptions that can occur at compile-time are called checked exceptions since they need to be explicitly checked and handled in code. Classes that directly inherit Throwable — except RuntimeException and Error — are checked exceptions e.g. IOExceptio n, InterruptedException etc.

Here is an example of a method that handles a checked exception:

public void writeToFile() < try (BufferedWriter bw = new BufferedWriter(new FileWriter("myFile.txt"))) < bw.write("Test"); >catch (IOException ioe) < ioe.printStackTrace(); >>

In this example, both statements within the try block (the instantiation of the BufferedWriter object and writing to file using the object) can throw IOException , which is a checked exception and therefore needs to be handled either by the method or its caller. In the example, IOException is handled within the method and the exception stack trace is printed to the console.

Furthermore, the BufferedWriter object is a resource, which should be closed when it is no longer needed and closing it can throw an IOException as well. In such cases where closing resources themselves can throw exceptions, using a try-with-resources block is best practice since this takes care of the closing of resources automatically. The example shown earlier uses try-with-resources for exactly this reason.

Unchecked Exceptions

Unchecked exceptions can be thrown «at any time» (i.e. run-time). Therefore, methods don’t have to explicitly catch or throw unchecked exceptions. Classes that inherit RuntimeException are unchecked exceptions e.g. ArithmeticException , NullPointerException .

Here is an example of a method that throws an unchecked exception (NullPointerException) which is not handled in code:

public void writeToFile() < try (BufferedWriter bw = null) < bw.write("Test"); >catch (IOException ioe) < ioe.printStackTrace(); >>

When the above method is called, a NullPointerException is thrown because the BufferedWriter object is null:

Exception in thread "main" java.lang.NullPointerException at IOExceptionExample.writeToFile(IOExceptionExample.java:10) at IOExceptionExample.main(IOExceptionExample.java:17)

As mentioned, since NullPointerException is an unchecked exception, it did not need to be handled in code — only the checked exception (IOException) was handled.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today!

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

Understanding Exception Hierarchy in Java Explained

he 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, which generally arise at either run- or compile-time. All of these Exceptions need to be handled to ensure the program runs in its natural flow.

Читайте также:  Php header ошибка 500

However, before you handle Exceptions, it would help to know what different kinds of Exceptions are present with Java. Through this article, let’s look at the various types of Exceptions in Java and the Exception Hierarchy that they follow.

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:

Ads of upGrad blog

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. Some examples of errors in Java are InternalError, AssertionError, OutOfMemoryError, etc.

Exceptions in Java are further divided into two categories:

  • 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.

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.

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

public static void print(String 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:

Читайте также:  Литература и примеры php

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:

try (BufferedWriter b_w = new BufferedWriter(new FileWriter(“myFile.txt”)))

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

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.

Explore Our Software Development Free Courses

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:

try (BufferedWriter b_w = null)

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)

Источник

Оцените статью