top of page
Writer's pictureThe Tech Platform

Exception Handling in Java

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.


Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.


By handling we make sure that all the statements execute and the flow of program doesn’t break.


The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:


Throwable

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



Exception

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. All the exception classes are derived directly or indirectly from the Exception class. They generally 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 Hierarchy


1. IOException

This class is the general class of exceptions produced by failed or interrupted I/O operations. As this is checked exception, it must be handled by the programmer else program does not compile.


Below are some of the scenarios when IOException would be thrown:

  • You were reading network file and got disconnected

  • reading local file which is not available any more

  • using some stream to read the data and some other process closes the stream

  • you are trying to read/write a file and don't have permission

  • you were writing a file and disk space is not available anymore


2. SQLException

The SQLException class provides information on a database access error.


Each SQLException provides several kinds of information:

  • a string describing the error. This is used as the Java Exception message, and is available via the getMesage() method

  • A "SQLstate" string which follows the XOPEN SQLstate conventions. The values of the SQLState string as described in the XOPEN SQL spec.

  • An integer error code that is vendor specific. Normally this will be the actual error code returned by the underlying database.

  • A chain to a next Exception. This can be used to provided additional error information.


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


4. RuntimeException

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. RuntimeException and all its exception subclasses are not checked by Java compiler because they occur during runtime of a program. That’s why these exceptions are also called unchecked exceptions.


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


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


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


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

  • StringIndexOutOfBoundsException

ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException exception is thrown when

an array element is accessed out of the index.

StringIndexOutOfBoundsException: StringIndexOutOfBoundsException exception is thrown when

a String or StringBuffer element is accessed out of the index.




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.


StackOverflowError

When a stack overflow occurs in an application because it has recursed too deeply.


VirtualMachineError

Indicate that the JVM is broken or has run out of resources, essential for continuing operating.


OutOfMemoryError

In case JVM cannot allocate an object as it is out of memory, such error is thrown that says no more memory could be made available by the GC.


Other errors in Java

AbstractMethodError

When a Java application tries to invoke an abstract method.


ClassCircularityError

While initializing a class, a circularity is detected.


IllegalAccessError

A Java application attempts either to access or modify a field or maybe invoking a method to which it does not have access.


ClassFormatErrorWhen JVM attempts to read a class file and find that the file is malformed or cannot be interpreted as a class file.


InstantiationError

In case an application is trying to use the Java new construct for instantiating an abstract class or an interface.


ExceptionInInitializerError

Signals that tell an unexpected exception have occurred in a static initializer.


InternalError

Indicating the occurrence of an unexpected internal error in the JVM.


IncompatibleClassChangeError

When an incompatible class change has occurred to some class of definition.


LinkageError

Its subclass indicates that a class has some dependency on another data.


NoSuchFieldError

In case an application tries to access or modify a specified field of an object, and after it, that object no longer has this field.


NoClassDefFoundError

If a class loader instance or JVM, try to load in the class definition and not found any class definition of the class.


ThreadDeath

Its instance is thrown in the victim thread when in thread class, the stop method with zero arguments is invoked.


NoSuchMethodError

In case an application tries to call a specified method of a class that can be either static or instance, and that class no longer holds that method definition.


UnsatisfiedLinkError

In case JVM is unable to find an appropriate native language for a native method definition.


UnsupportedClassVersionError

When the JVM attempts to read a class file and get to know that the major & minor version numbers in the file are unsupportable.


UnknownError

In case a serious exception that is unknown has occurred in the JVM.


VerifyError

When it is found that a class file that is well-formed although contains some sort of internal inconsistency or security problem by the verifier.


 

Example:


public class JavaExceptionExample{
  public static void main(String args[]){
   try{
      int data=100/0;
   }catch(ArithmeticException e){System.out.println(e);}
   System.out.println("rest of the code...");
  }
}

Output:


 

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

  1. Checked Exception

  2. Unchecked Exception

  3. Error


1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.


List of Checked Exception in Java
  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.


2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.


List of Unchecked Exception in Java
  • 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.

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

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

a. NumberFormatException

b. IllegalThreadStateException


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


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

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

a. ArrayIndexOutOfBoundsException

b. StringIndexOutOfBoundsException


a. ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException exception is thrown

when an array element is accessed out of the index.

b. StringIndexOutOfBoundsException: StringIndexOutOfBoundsException exception is thrown

when a String or StringBuffer element is accessed out of the index.

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

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

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

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

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


3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


 

Difference between Exception and Error

Exception

Error

Can be handles

Cannot be handled

Can be checked type or unchecked type

Errors are of unchecked type

Thrown at runtime only, but the checked exceptions known by the compiler and the unchecked are not

Occurs at the runtime of the code and is not known to the compiler

The y are defined in java.lang.Exception

They are defined in java.lang.error package

Program implementation mistakes cause exceptions

Error are mainly caused because of the environment of the program where it is executing


 

Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword

Description

try

The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.

catch

The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally

The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.

throw

The "throw" keyword is used to throw an exception.

throws

The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.



Advantages of Exception Handling in Java

  • Separating Error-Handling Code from “Regular” Code

  • Propagating Errors Up the Call Stack

  • Grouping and Differentiating Error Types



Disadvantages of Exception Handling in Java

  • Experiencing unnecessary overhead

  • Not understanding how the application really works

  • Filling your logs with noisy events

  • Inability to focus on what actually matters



Source: Wikipedia , javapoint


The Tech platform

0 comments

Comments


bottom of page