Exception Handling in Java

Rumman Ansari   Software Engineer   2022-11-01   8710 Share
☰ Table of Contents

Table of Content:


An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually—typically through the use of error codes

AJava exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.

So, in short What is exception

exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

  • A user has entered an invalid data.

  • A file that needs to be opened cannot be found.

  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

Hierarchy of Java Exception classes

Exceptions are objects, and objects are defined using classes. The root class for exceptions is java.lang.Throwable

java exception handling

System errors are thrown by the JVM and are represented in the Error class. The Error class describes internal system errors, though such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Examples of subclasses of Error are listed in table below.

Class Reasons for Exception
LinkageError A class has some dependency on another class, but the latter class has
changed incompatibly after the compilation of the former class.
VirtualMachineError The JVM is broken or has run out of the resources it needs in order to
continue operating.

Exceptions are represented in the Exception class, which describes errors caused by your program and by external circumstances. These errors can be caught and handled by your program. Examples of subclasses of Exception are listed in table below.

Class Reasons for Exception
ClassNotFoundException Attempt to use a class that does not exist. This exception would occur, for example, if you tried to
run a nonexistent class using the java command, or if your program were composed of, say,
three class files, only two of which could be found.
IOException Related to input/output operations, such as invalid input, reading past the end of a file, and opening
a nonexistent file. Examples of subclasses of IOException are InterruptedIOException ,
EOFException (EOF is short for End of File), and FileNotFoundException

Runtime exceptions are represented in the RuntimeException class, which describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Runtime exceptions are generally thrown by the JVM. Examples of subclasses are listed in table below.

Class Reasons for Exception
ArithmeticException Dividing an integer by zero. Note that floating-point arithmetic
does not throw exceptions (see Appendix E, Special Floating-
Point Values).
NullPointerException Attempt to access an object through a  null reference variable.
IndexOutOfBoundsException Index to an array is out of range.
IllegalArgumentException A method is passed an argument that is illegal or inappropriate.

Exception are categorized into 3 category.

    • Checked Exception

The exception that can be predicted by the programmer at the compile time.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.

    • Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.

    • Error

Errors are typically ignored in code because you can rarely do anything about an error. Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the code.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int vara=50/0;//ArithmeticException  

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

String strng=null;  
System.out.println(strng.length());//NullPointerException  


3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.

<
String strng="abc";  
int i=Integer.parseInt(strng);//NumberFormatException  


4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:

int array[]=new int[5];  
array[10]=50; //ArrayIndexOutOfBoundsException