Exception Handling in Java with Example

Exception handling in Java is the most significant component of Java Programming. It allows you to handle runtime errors in your program.

In this chapter, we will talk about what is an Exception, types of exception, and Handling Exception in Java with examples.

What is an Exception?

In Java, Exception is an abnormal/unusual condition that may occur during the execution of a program.  Java program will get terminates if an exception occurs.

Therefore, to avoid any kind of unexpected shutdown of a program during runtime we need to handle exceptions.

In the case of program termination, a system-generated error will be thrown. The good thing is that we can handle these exceptions and set our custom and meaningful error messages.

Difference between Exception and Error?

This is the trickiest part in Exception handling to understand the core differences between Error and Exception.

In layman’s terms:

Error: Error is irrecoverable and indicates a serious problem.

Exception: Exception can be handled by a programmer and can be predicted.

  • Both Errors and Exceptions are the subclasses of java.lang.Throwable class

Remember:

ErrorException
1. An error can’t be predicted.1. An exception can be predicted.
2. You can’t recover from an error.2. You can handle exception during code.
3. All errors are unchecked type and thrown by JVM3. Exceptions are known to the compiler.
4. Example: StackOverFlowError, OutOfMemoryError4. Example: NullPointerException, ArrayIndexOutOfBoundsException

Why Exception Occurs?

There can be multiple reasons a program can throw an Exception. For example, getting value from an empty list or opening a file that doesn’t exist.

But these types of errors are predictable and can be easily handled by the programmer.

Java Exception Keywords

  • try: We place our code inside TRY block where an exception can occur at runtime.
  • catch: To handle the exception, we use catch block and it is placed just after TRY block.
  • finally: It is used to execute a crucial part of the code, It is executed whether an exception is handled or not.
  • throw: It is used to throw an exception.
  • throws: It defines that there may occur an exception. It is used to declare an exception.

Exception Handling in Java – How to Handle an Exception?

Now, we will learn exception handling in Java. To do so, we use TRY-CATCH block.

We place our code inside TRY block where an exception can occur, followed by a CATCH block.

For example:

public class Demo{  
  public static void main(String args[]){  
   try{  
      //code that may raise exception  
      int data = 100/0;  
   }catch(ArithmeticException e){
      //handling exception and printing it
      System.out.println(e);
    }  
   //rest code of the program   
  }  
}

Advantage of Exception Handling

  • A program will never break at runtime.
  • Custom error messages.
  • Good Programming Practise.

Types of Exceptions in Java

Basically, there are two types of Exceptions in Java:

  1. Checked Exception
  2. Unchecked Exception

1.) Checked Exception in Java:

Checked exceptions are checked by the compiler at compile-time and it will throw an error if any checked exception is not handled in the program.

For example, SQLException, IOException, ClassNotFoundException etc.

2.) Unchecked Exception in Java:

Runtime exceptions are known as unchecked exceptions and they may occur at runtime. The compiler will not check these exceptions during the compilation of the program.

These types of exceptions are abnormal.

For example, NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException etc.

Java Exception Handling Example

public class Practise {

public static void main(String args[]) {
	try {
		// code that may raise exception
		int data = 100 / 0;
	} catch (ArithmeticException e) {
		System.out.println("Inside the catch block " + e);
	} catch (Exception e) {
		System.out.println("Inside the catch block " + e);
	} finally {
		System.out.println("Inside the finally block");
	}
	// rest code of the program
	System.out.println("rest of the code...");
 }
}

Points to Remember:

  • Try block can’t be written alone. It will always appear with the Finally or Catch block.
  • We can use multiple Catch blocks at the same time.
  • Catch or Finally are always written after TRY block.
  • The program will always enter into Finally block whether an exception is handled or not.

That’s it for exception handling in Java. Hope you learn something new or refresh your memory. Will see further usage in the next chapter.