Java root exception class

Exception Handling in Java: Hierarchy Example and Types

Here we will discuss basics of exceptions, Why Exception handling and its types.

What is Exception in Java

A unwanted event that disrupts the program execution.

In Java all Exceptions are class.

Why Exception Occurs

Example of Exceptions

  1. Dividing a number by zero 5/0 . It will throw ArithmeticException
  2. Converting a String to number Integer.parseInt(«123s») . Exception It will throw NumberFormatException
  3. Accessing beyond index in Array a[100] when only 5 elements are in array. Throw ArrayIndexOutOfBoundsException

ArithmeticException on Java Program

What is Exception Handling in Java

Exception can terminate the program execution.

To handle unwanted event and to execute rest of the program exception handling is required

On exception Java shows programmer friendly message. To show end used we need to provide custom message

How to Handle Exception in Java

Java provides keywords to handle the exception

Java exception can be handle by 5 keyword try, catch, throw, throws and finally.

  1. try : Any Program statement that we want to check for exception must be placed within a try block.
  2. catch : If the exception occurs within try block it is thrown. Your code can catch this exception (using catch) and handle it.
  3. throw : if an exception arises then this system-generated exception is automatically thrown by Java run time system. To manually throw an exception, throw keyword used.
  4. throws : A throws clause lists the type of exception that a method might throw.
  5. finally : In programming, we want any code must be executed after the try block completes is placed within a finally block.

try block can be used either with a catch or finally block or with both but try cannot be used alone.

A try can have multiple catch block.

When there is an exception in the try block an appropriate catch block is executed based on the exception.

Exception Hierarchy in java

In java programming, Exception class is a subclass of class Throwable.

Apart from the Exception class, class Error is also derived from class Throwable.

Java Exception Hierarchy

Error: In java programming, error is Unrecoverable. It occurs during compile time.

For example, if we write wrong syntax then error will generate during compile time.

Root class of exception in java

Throwable is the root class of exception in Java

Types of Exception in Java

Checked Exception in java

Exceptions that are checked by compiler is called checked exceptions.

On compiling above program.

Checked Exception in Java

To make code executable we must surround Scanner with try and catch the FileNotFoundException.

Here is the list of some checked exception

  1. IllegalAccessException: in java programming, this exception occurs when access to a class is denied.
  2. ClassNotFoundException: this exception occurs when class not found.
  3. NoSuchMethodException : when a requested method dose not exist this exception occurs.
  4. CloneNotSupportedException: in java programming ,If you are trying to use the clone method in a classwhere Cloneable interface is not implemented, it throwsCloneNotSupportedException. Clone() method is used to create exactcopy of a object
  5. InterruptedException : in java , when we work with multiple threads then one thread interrupts another thread.
Читайте также:  Подмена ip адреса python

Unchecked Exception in Java

Exception condition is not checked by compiler.

Runtime class and its sub classes are known as unchecked exception.

Источник

Exception Hierarchy in Java | Types of Exceptions

Scientech Easy

In this tutorial, we will learn exception hierarchy in Java with diagrams and brief descriptions.

In the previous tutorial, we have explained basic points of exception handling, and exception handler in Java with realtime examples.

I will recommend that you first familiarize the basic points.

Types of Exceptions in Java

Basically, there are two types of exceptions in java API. They are:

  1. Predefined Exceptions (Built-in-Exceptions)
  2. Custom Exceptions

Predefined Exceptions:

Predefined exceptions are those exceptions that are already defined by Java system. These exceptions are also called built-in-exceptions.

Java API supports exception handling by providing the number of predefined exceptions. These predefined exceptions are represented by classes in java.

When a predefined exception occurs, JVM (Java runtime system) creates an object of predefined exception class. All exceptions are derived from java.lang.Throwable class but not all exception classes are defined in the same package.

All the predefined exceptions supported by java are organized as subclasses in a hierarchy under the Throwable class.

The Throwable class is the root of exception hierarchy and is an immediate subclass of Object class. Let’s understand the java exception hierarchy, as shown in the below figure.

Java exception hierarchy

1. Throwable class: As shown in the above figure, Throwable class which is derived from Object class, is a top of exception hierarchy from which all exception classes are derived directly or indirectly. It is the root of all exception classes. It is present in java.lang package.

Throwable class is the superclass of all exceptions in java. This class has two subclasses: Error and Exception. Errors or exceptions occurring in java programs are objects of these classes. Using Throwable class, you can also create your own custom exceptions.

2. Error: Error class is the subclass of Throwable class and a superclass of all the runtime error classes. It terminates the program if there is problem-related to a system or resources (JVM).

An error generally represents an unusual problem or situation from which it is difficult to recover. It does not occur by programmer mistakes. It generally occurs if the system is not working properly or resource is not allocated properly.

VirtualMachineError, StackOverFlowError, AssertionError, LinkageError, OutOfMmeoryError, etc are examples of error. We will learn more detail in further tutorials.

3. Exception: It is represented by an Exception class that represents errors caused by the program and by external factors. Exception class is a subclass of Throwable class and a superclass of all the exception classes.

Читайте также:  Interface for constructor java

All the exception classes are derived directly or indirectly from the Exception class. They originate from within the application.

The exception class provides two constructors:

  • public Exception() (Default constructor)
  • public Exception(String message) (It takes a message string as argument)

Each of the exception classes provides two constructors: one with no argument and another with a String type argument. Exception class does not provide its own method. It inherits all methods provided by Throwable class.

Exception Class Hierarchy in Java

We can see the hierarchy of exception class in Java in the below figure that is very important for an interview purpose.

Exception class in Java exception hierarchy

Custom Exceptions:

Custom exceptions are those exceptions that are created by users or programmers according to their own needs. The custom exceptions are also called user-defined exceptions that are created by extending the exception class.

So, Java provides the liberty to programmers to throw and handle exceptions while dealing with functional requirements of problems they are solving. We will discuss in more detail about custom exceptions in further tutorials.

Let’s see the brief description of each subclass of the Exception class.

RuntimeException class (Unchecked Exceptions)

RuntimeException class is a subclass of the Exception class. It is thrown by JVM or programmatically when an arithmetic operation performed in the program is incorrect or defect/bug occurs in the program’s code.

Java compiler does not check RuntimeException and all its exception subclasses because they occur during runtime of a program. That’s why these exceptions are also called unchecked exceptions.

RuntimeException class consists of many other exception subclasses that are used to handle a specific type of exception.

Apart from these exception subclasses of RuntimeException class shown in the above figure. There are other subclasses of RuntimeException class, which have not been shown in the hierarchy structure diagram to avoid complexity.

Let’s see a brief description of them.

1. ArithmeticException: This exception is thrown when arithmetic problems, such as a number is divided by zero, is occurred. That is, it is caused by maths error.

2. ClassCastException: The ClassCastException is a runtime exception that is thrown by JVM when we attempt to invalid typecasting in the program. That is, it is thrown when we cast an object to a subclass of which an object is not an instance.

3. IllegalArgumentException: This runtime exception is thrown by programmatically when an illegal or appropriate argument is passed to call a method. This exception class has further two subclasses:

NumericFormatException: NumberFormatException is thrown by programmatically when we try to convert a string into the numeric type and the process of illegal conversion fails. That is, it occurs due to the illegal conversion of a string to a numeric format.

IllegalThreadStateException: IllegalThreadStateException exception is a runtime exception that is thrown by programmatically when we attempt to perform any operation on a thread but it is incompatible with the current thread state.

4. IndexOutOfBoundsException: This exception class is thrown by JVM when an array or string is going out of the specified index. It has two further subclasses:

ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException exception is thrown when an array element is accessed out of the index.

Читайте также:  Php cms система управления содержимым cms

StringIndexOutOfBoundsException: StringIndexOutOfBoundsException exception is thrown when a String or StringBuffer element is accessed out of the index.

5. NullPointerException: NullPointerException is a runtime exception that is thrown by JVM when we attempt to use null instead of an object. That is, it is thrown when the reference is null.

6. ArrayStoreException: This exception occurs when we attempt to store any value in an array which is not of array type. For example, suppose, an array is of integer type but we are trying to store a value of an element of another type.

7. IllegalStateException: The IllegalStateException exception is thrown by programmatically when the runtime environment is not in an appropriate state for calling any method.

8. IllegalMonitorStateException: This exception is thrown when a thread does not have the right to monitor an object and tries to access wait(), notify(), and notifyAll() methods of the object.

9. NegativeArraySizeException: The NegativeArraySizeException exception is thrown when an array is created with a negative size.

List of Checked Exceptions in Java

Now, we have listed checked exceptions in a brief description.

1. ClassNotFoundException: The ClassNotFoundException is a kind of checked exception that is thrown when we attempt to use a class that does not exist.

Checked exceptions are those exceptions that are checked by the Java compiler itself.

2. FileNotFoundException: The FileNotFoundException is a checked exception that is thrown when we attempt to access a non-existing file.

3. InterruptedException: InterruptedException is a checked exception that is thrown when a thread is in sleeping or waiting state and another thread attempt to interrupt it.

4. InstantiationException: This exception is also a checked exception that is thrown when we try to create an object of abstract class or interface. That is, InstantiationException exception occurs when an abstract class or interface is instantiated.

5. IllegalAccessException: The IllegalAccessException is a checked exception and it is thrown when a method is called in another method or class but the calling method or class does not have permission to access that method.

6. CloneNotSupportedException: This checked exception is thrown when we try to clone an object without implementing the cloneable interface.

7. NoSuchFieldException: This is a checked exception that is thrown when an unknown variable is used in a program.

8. NoSuchMethodException: This checked exception is thrown when the undefined method is used in a program.

Key Points to Remember:

  • Two types of exceptions in Java: Predefined and Custom exceptions.
  • The root class for all the exceptions in the hierarchy of exception classes is java.lang.Throwable.
  • Exception classes are mainly divided into three types: system errors, exceptions, and runtime exceptions.
  • System errors are represented by Error class and thrown by JVM.
  • Exceptions are represented by Exception classes that describe errors in your program.

Hope that this tutorial has covered almost all the basic points related to the exception hierarchy in java. I hope you will have understood the basic points of Throwable class and its subclasses: Exception and Error.

In the next tutorial, we will learn another important topic checked and unchecked exception in Java.
Thanks for reading.

Источник

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