Home  >  Blog  >   Java

Exception Handling in Java

Rating: 4
  
 
2438
  1. Share:
Java Articles

Exception handling is a powerful mechanism of Java to take care of the runtime errors without interrupting the normal flow of the program. 

Are you interested in taking up Core Java Certification Training? Enroll Now for Core Java Training!

 

 

What is an Exception?

An exception is an abnormal or unwanted condition that occurs during the program execution and disrupts the flow of the program.

The core advantage of exception handling is to maintain the flow of the program. Let us understand this by one example:

Consider a program is of 10 expressions like shown below:

Expr 1;  
Expr 2;  
Expr 3;  
Expr 4;  
Expr 5;
Expr 6;  //exception occurs  
Expr 7;  
Expr 8;  
Expr 9;  
Expr 10;  

Now if there is an exception occurring at expression 6, the rest of the code after that will not be executed. In this case expr7 to 10 will be ignored. Now if we include exception handling in our code, rest of the expressions will be executed. 

Exception Vs Error

Exception: Exception occurs in the program which can be resolved and handled in program code. There are 2 types of exceptions available:

  1. Checked Exception: Checked exceptions are verified at compile time only. They must be handled by the programmer in code. If not, then we will be getting a compiler error. Some of the checked exceptions are SQLException, FileNotFoundException, IOException, etc.  
  2. Unchecked Exception: Unchecked exceptions are not checked by the compiler while compiling the code.  They are checked at runtime only. For example, NullPointerException ,ArithmeticException, ArrayIndexOutOfBoundsException etc.  In Selenium we will be handling unchecked exceptions like StaleElementReferenceException,  TimeoutException, NoSuchWindowException, NoSuchElementException etc.

Error: Error cannot be resolved by a programmer. They are irrecoverable. Error is also one type of unchecked exception. They occur due to some scarcity of system resources. For Example JVM Error, Stack overflow, hardware error, etc.

 MindMajix YouTube Channel

Exception Keywords in Java

Below 5 keywords are used to handle exceptions in Java.

  1. try: The “try” keyword is the indicator of a block where we need to put our exception code. The “try” block cannot be used alone. It must be accompanied with a catch or finally.
  2. catch: The “catch” block cannot be used standalone. It must be used along with “try” block. It is used to handle the exception. Multiple catch blocks are possible in Java to handle multiple types of exceptions. 
  3. finally: The “finally” block is used to execute the cleanup code in the program. It will be executed irrespective of whether the exception is handled or not. There should be only one “finally” block even if the code is having multiple tries...catch block.
  4. throw: The “throw” keyword is entered to throw a manual exception. 
  5. throws: The "throws" keyword is used to declare exceptions. It is not used to throw an exception. It indicated the possibility of exception in the method. It must always be used with a method signature. 

Exception Handling Example

Let us go through different examples of Exception Handing in Java.

  • try…catch block: In this example, we can see that after handling an exception, control is being passed to the next statement written after try…catch block.
public class DemoException{  
public static void main(String args[]){  
try
{  
   int d=10/0;  
}
 catch (ArithmeticException e)
 {
    System.out.println("Catch block"+ e);
 }  
 
 System.out.println("rest of the code");  
}  
}  

Output:

Catch block Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code
  • try…catch…finally block: As discussed, we can have one try block followed by multiple catch blocks to handle multiple types of exceptions. The “finally” block is executed even if exception rises or not.
public class DemoException {
    public static void main(String[] args) {
         try
          {
           int a[]={4,8,9};
           System.out.println(a[2]);
           //a[3]=1;// if this line is uncommented then this statement will raise exception of type ArrayIndexOutobouncException. In this case control will got to that block which is handling this exception
           int x=10;
           System.out.println(x/0);
           
          } 
          catch(ArithmeticException e1)
          {
           System.out.println("number cannot divided by zero"+e1);
          }
          catch(ArrayIndexOutOfBoundsException e2)
          {
           System.out.println("array index out of bound exception"+e2);
          }
          catch(Exception e)
          {
             System.out.println(e);// when any matching exception is not handled then control will come to this block.
          }
          finally
          {
              System.out.println("in finally block"); //this will be executed even if exception is handled or not.
          }
         System.out.println("After try catch finally block");
    }
 
}

Output:

9
number cannot divided by zerojava.lang.ArithmeticException: / by zero
in finally block
After try catch block
  • throw: The “throw” keyword is entered in code to throw an exception manually by a programmer. In below code we are throwing an arithmetic exception by giving our own message to display.
public class throwDemo{
public static void main(String[] args) {
        throw new ArithmeticException("throwing  arithmetic exception"); 
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: throwing  arithmetic exception at throwDemo.main(throwDemo.java:4)
  • throws: The “throws” keyword is used with method signature to mention that this method might throw exception. To avoid dealing with try and catch block, we can simply write throws expression to avoid any compile-time error. 
public class ThrowsExceptionDemo {
    public static void main(String[] args) throws FileNotFoundException {
        openF("G:	est.txt");
        
    }
    public static void openF(String fname) throws FileNotFoundException{
        FileInputStream f= new FileInputStream(fname);
        
    }
}

Java’s Built-In Exceptions

Java has some in-built in exception classes inside the standard package java.lang. You might have faced some of those exceptions till now.  These unchecked exceptions must be included in any method’s throw list if that method is supposed to trigger that exception and it is not handled there.

Below is the list of in-built unchecked and checked exceptions provided by Java with its meaning.

Unchecked ExceptionMeaning
ArithmeticExceptionArithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds
IllegalArgumentExceptionIllegal argument used to invoke a method.
IndexOutOfBoundsExceptionSome type of index is out-of-bounds.
NullPointerExceptionInvalid use of a null reference.
NumberFormatExceptionInvalid conversion of a string to a numeric format.
StringIndexOutOfBoundsAttempt to index outside the bounds of a string.
TypeNotPresentExceptionType not found.
Checked ExceptionMeaning
ClassNotFoundExceptionClass not found
IllegalAccessExceptionAccess to a class is denied
InstantiationExceptionAttempt to create an object of an abstract class or interface.
InterruptedExceptionOne thread has been interrupted by another thread
NoSuchFieldExceptionA requested field does not exist.
NoSuchMethodExceptionA requested method does not exist.
Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Core Java TrainingMar 30 to Apr 14View Details
Core Java TrainingApr 02 to Apr 17View Details
Core Java TrainingApr 06 to Apr 21View Details
Core Java TrainingApr 09 to Apr 24View Details
Last updated: 03 Apr 2023
About Author

Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15