Skip to content

Exceptions In Java Programming Language

In this article, you are going to learn Exceptions in Java Programming Language.

An exception is an unwanted event that occurs when a java program is executed which results in a disruption in the normal flow of the program or simply an application.

Also Read:- Data Structures in Java Programming Language

The program or an application immediately gets terminated when an exception occurs. So it is very important to maintain the normal flow of the application and handle the errors which is done through using various keywords provided by java which we will discuss later in this article in the exception handling section.

But, let’s first understand the reason why these exceptions occur.

WHY EXCEPTIONS OCCURS IN JAVA

Following are some reasons behind occurrence of an exception in java programming language.

  • Java Virtual Machine(JVM) runs out of memory.
  • File necessary to run a particular program is not found.
  • Invalid data entered by the user.
  • The network connection is not working properly .

TYPES OF EXCEPTIONS IN JAVA

  1. Checked Exceptions
  2. Unchecked Exceptions
  3. Errors

[1] CHECKED EXCEPTIONS

Exceptions that occur at the compile-time are known as the Checked Exceptions. These are also known as Compile-time exceptions. For example; IOException, SQLException, FileNotFoundException etc.

Example:

class FileNotFoundExample {
public static void main(String args[]) {
File fileobj = new File(“C ://hello.txt”) ;
FileInputStream fobj = new FileInputStream (fileobj) ;
}
}

Output:

Main.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileInputStream fobj = new FileInputStream (fileobj) ;
^
1 error

[2] UNCHECKED EXCEPTIONS

Exceptions that occur at the run-time(execution time) are known as Unchecked Exceptions. These are also known as Run-time Exceptions. For example; NullPointerException, ArithmeticException, NumberFormatException, ArrayIndexOutOfBoundsException etc.

Example:

class UncheckedException {
public static void main(String args[]) {
int division = 65/0 ;
System.out.println(“ArithmeticException Example”) ;
}
}

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at UncheckedException.main(Main.java:9)

[3] ERRORS

An error is something that cannot be recovered by a programmer. For Example; VirtualMachineError, StackOverflowError, OutOfMemoryError, AbstractMethodError, ClassFormatError, LinkageError, InternalError etc.

EXCEPTION CLASSES IN JAVA

exception-in-java

Checked Exceptions

  • IllegalAccessException
  • ClassNotFoundException
  • CloneNotSupportedException
  • InstantiationException
  • NoSuchFieldException
  • InterruptedException
  • NoSuchMethodException
  • IOException
  • SQLException
  • FileNotFoundException

Unchecked Exceptions

  • ArithmeticException
  • ArrayStoreException
  • IllegalArgumentException
  • IllegalStateException
  • IndexOutOfBoundsException
  • NullPointerException
  • SecurityException
  • UnsupportedOperationException
  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • IllegalMonitorStateException
  • IllegalThreadStateException
  • NegativeArraySizeException
  • NumberFormatException
  • StringIndexOutOfBounds
  • EmptyStackException
  • BufferUnderflowException
  • MissingResourceException
  • CMMException

Errors

  • AbstractMethodError
  • ClassCircularityError
  • AssertionError
  • ExceptionInInitializerError
  • InstantiationError
  • IllegalAccessError
  • IncompatibleClassChangeError
  • NoClassDefFoundError
  • NoSuchMethodError
  • NoSuchFieldError
  • StackOverflowError
  • VirtualMachineError
  • VerifyError
  • UnsatisfiedLinkError
  • ThreadDeath
  • OutOfMemoryError
  • UnknownError

EXCEPTION HANDLING IN JAVA

In java programming language, exception handling is the technique of managing the java exceptions in order to eliminate disruption in the normal flow of a java program or an application.

The following keywords are used for exception handling in java programming language.

  • try
  • catch
  • finally
  • throw
  • throws

TRY BLOCK

The try block is used within the method to enclose the codes that are likely to generate an exception. In order to handle the exception, the combination of either try-catch block or try-finally block is used.

(A) TRY CATCH BLOCK

In this combination, the try block encloses the code that is likely to cause an exception and the catch block handles the exception. The catch block can also be used multiple times which we will discuss later in this article.

Syntax:

try {
// code that is likely to cause exception
}
catch(ExceptionClassName ref) {
}

Example 1: We have shown below an example without using try-catch exception handling

class TryCatch {
public static void main(String args[]){
int division = 65/0 ;
System.out.println(“Try Catch Example”) ;
}
}

Output 1: You will get the following output after executing the above java codes.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at TryCatch.main(Main.java:9)

Example 2: Applying try-catch block to the above example.

class TryCatch {
public static void main(String args[]) {
try{
int division = 65/0 ;
}
catch(ArithmeticException ref) {
System.out.println(ref) ;
}
System.out.println(“Try Catch Example”) ;
}
}

Output 2: You will get the following output after applying the try-catch block.

java.lang.ArithmeticException: / by zero
Try Catch Example

(B) TRY FINALLY BLOCK

In this combination, the try block is followed by a finally block which is designed to execute the codes in any condition and is not affected by the exception occurred.

Syntax:

try {
// code that is likely to cause exception
}
catch(ExceptionClassName1 ref1) {
}
catch(ExceptionClassName2 ref2) {
}
finally {
}

Example:

class TryFinallyBlock {
public static void main(String args[]) {
try {
int division = 65/0 ;
System.out.println(division) ;
}
catch(ArithmeticException ref) {
System.out.println(ref) ;
}
finally {
System.out.println(“Finally Block Executed”) ;
}
System.out.println(“Example of TryFinally Block”) ;
}
}

Output:

java.lang.ArithmeticException: / by zero
Finally Block Executed
Example of TryFinally Block

MULTIPLE CATCH BLOCKS

Multiple catch blocks are used to handle more than one exceptions occurring in a java program.

Example:

class MultipleCatchBlockExample {
public static void main(String args[]) {
try {
int arr[] = new int[4] ;
arr[4] = 28/0 ;
}
catch(ArithmeticException ref) {
System.out.println(“Exception1 is handled”) ;
}
catch(ArrayIndexOutOfBoundsException ref) {
System.out.println(“Exception2 is handled”) ;
}
catch(Exception ref) {
System.out.println(“Exception3 is handled”) ;
}

System.out.println(“Example of Multiple Catch Block”) ;
}
}

Output:

Exception1 is handled
Example of Multiple Catch Block

Also Read: Nested Classes in Java Programming Language

We have provided you the best possible description on Exceptions in Java Programming Language. Hope you like this post. For more updates and related information, stay connected to our blogs on java programming language.

Facebook
Twitter
LinkedIn
Pinterest