Exception Handling in Java

Exception handling in Java

Today in this article we will be discussing about exceptional handling in Java.

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.

Multithreading in Java

Exception Handling is a mechanism for dealing with runtime errors like ClassNotFoundException, IOException, SQLException, RemoteException, and so on.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let’s consider a scenario:

  • statement 1;  
  • statement 2;  
  • statement 3;  
  • statement 4;  
  • statement 5;//exception occurs  
  • statement 6;  
  • statement 7;  
  • statement 8;  
  • statement 9;  

Suppose there are 9 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 9 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in java

Exception-Handling-in-Java

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

  1. Checked Exception
  2. Unchecked Exception
  3. Error

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription