Exceptions class hierarchy in java

Exceptions class hierarchy in java

Базовым классом для всех исключений является класс Throwable . От него уже наследуются два класса: Error и Exception . Все остальные классы являются производными от этих двух классов.

Класс Error описывает внутренние ошибки в исполняющей среде Java. Программист имеет очень ограниченные возможности для обработки подобных ошибок.

Собственно исключения наследуются от класса Exception. Среди этих исключений следует выделить класс RuntimeException . RuntimeException является базовым классом для так называемой группы непроверяемых исключений (unchecked exceptions) — компилятор не проверяет факт обработки таких исключений и их можно не указывать вместе с оператором throws в объявлении метода. Такие исключения являются следствием ошибок разработчика, например, неверное преобразование типов или выход за пределы массива.

Некоторые из классов непроверяемых исключений:

  • ArithmeticException : исключение, возникающее при делении на ноль
  • IndexOutOfBoundException : индекс вне границ массива
  • IllegalArgumentException : использование неверного аргумента при вызове метода
  • NullPointerException : использование пустой ссылки
  • NumberFormatException : ошибка преобразования строки в число

Все остальные классы, образованные от класса Exception, называются проверяемыми исключениями (checked exceptions).

Некоторые из классов проверяемых исключений:

  • CloneNotSupportedException : класс, для объекта которого вызывается клонирование, не реализует интерфейс Cloneable
  • InterruptedException : поток прерван другим потоком
  • ClassNotFoundException : невозможно найти класс

Подобные исключения обрабатываются с помощью конструкции try..catch. Либо можно передать обработку методу, который будет вызывать данный метод, указав исключения после оператора throws:

public Person clone() throws CloneNotSupportedException

В итоге получается следующая иерархия исключений:

Иерархия классов исключений в Java

Поскольку все классы исключений наследуются от класса Exception, то все они наследуют ряд его методов, которые позволяют получить информацию о характере исключения. Среди этих методов отметим наиболее важные:

  • Метод getMessage() возвращает сообщение об исключении
  • Метод getStackTrace() возвращает массив, содержащий трассировку стека исключения
  • Метод printStackTrace() отображает трассировку стека

Источник

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:

Читайте также:  Var data type in javascript

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.

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.

Читайте также:  Standard error stream in python

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

Источник

Exception Hierarchy in Java

Whenever any unexpected event like if required Index is more than the array size happens, it results in the stopping of the program. The name of this condition is an “Exception”.

There are many types of exceptions occurred in java, and there is a certain hierarchy followed by java. We will be exploring this hierarchy through this blog.

“Throwable class” is the topmost class in the hierarchy. It is mainly divided into 2 types which are Exception class and Error class.

Exception Hierarchy in Java

Errors

Errors are problems that are happening due to failures in the system or Java virtual machine (JVM). One common example of an error can be a system crash. Errors can only occur when we are running a program (runtime), this is the reason error is an unchecked type.

Here is an example of an Error:

Читайте также:  Java 301 64 bit

Explanation:

In the above code, we can see that the print function is calling itself again and again, there is no ending for this function call. This results in the filling of the Stack and we get the “StackOverflowError”. It cannot be solved directly with the use of debugging.

Exceptions

Exceptions are errors happening due to problems in the code/program. It can occur at either runtime (unchecked exception) or compile time (checked exception). The checked exception are needed to be corrected through the program although unchecked exceptions need not be solved precisely.

Here is an example of an Exception:

//Since dividing any number by 0 will result into an infinite number so we will give 0 as second number

Explanation:

In the above code, we are dividing any particular numeric value with 0. This is not possible as it will result in an infinite number. As division is an Arithmetic Operation and it cannot be performed in this case therefore the “ArithmeticException” occurs.

Custom Exceptions

“Custom” word states that the complete functionality of any application is designed by the person . So custom exceptions are created by the coder according to the need of the program. Therefore it is also known as user defined exceptions. This is one of the advantages that java includes, i.e, giving the choice to programmers to create their exceptions.

Explanation:

In the starting, we are creating a child class of Exception class naming it as invalidgender class. Now we will create a constructor of the invalidgender class, and call the constructor of the Exception class using super keyword.

While declaring the main function we will write throws invalidgender, throws keyword will help the program to get the information about the invalidgender exception.

If-else condition is used to find whether the written gender is either male or female. If it is either male or female we will go inside the if-condition and print the entered the gender. Otherwise we are going to call the invalidgender exception.

The argument passed as an string inside the invalidgender exception will be printed.

There are two types of predefined exceptions in java:

1. Checked Exceptions

Exceptions which are having the probability to arise while compiling are known as checked exceptions. These type of exceptions are needed to be handled specifically and can’t be ignored. You can handle checked exceptions using try-catch block.

For Example: If the user is trying to access a file which is not even created yet, then the program will return a File Not Found Exception.

Источник

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