Loading

What is an Exception in Java?

  • An exception is an event that occurred in JVM which disturbs the normal flow of execution.
  • The exception may occur due to the code or due to the environment of the execution.
  • When the exception occurs we must handle the exception otherwise the program will get terminated abruptly.

Key Points:

  • An exception handling can be defined by using a try-catch block.
  • In order to define exception handling we must know the exception type and exception name.
  • We can have any number of try-and-catch blocks.
  • the catch block is always followed by the try block.
  • catch block can handle any number of exceptions in one single block.

Syntax:

try{
       // try block statements
}
catch(Exception_name reference){
      // catch block statements
}

Example:

package quipoin;

public class DemoForCatchBlock {
	public static void main(String[] args) {
		try {
			int data = 10 / 0;
			System.out.println(data);

		} catch (NullPointerException e) { // 1st catch block
			e.printStackTrace();
		} catch (ArithmeticException e) { // 2nd catch block
			System.out.println("Cannot be divided by zero!!");
			e.printStackTrace();
		}
	}
}

Output:

Cannot be divided by zero!!
java.lang.ArithmeticException: / by zero
	at DemoForCatchBlock.main(DemoForCatchBlock.java:4)

In the above example the JVM searches for the handler in 1st catch block, if the exception type is matched with the exception occurs it will execute(1st block) if not then the JVM searches for the handler in 2nd catch block.


How does an exception occur?

  • During execution, if the JVM encounters an event that cannot perform an operation, the JVM will create an object of throwable type and it will throw the object back to the code.
  • In the code, if the try-catch block is defined the JVM will execute the catch block and continue the execution.
  • If there is no handler(catch block) defined in the code the JVM terminates the execution abruptly.
  • The object is thrown by using the throw keyword, the syntax to throw a new NullPointerException.
  • We can write our own code to throw the throwable type object.
  • While defining the catch block the catch block parameter should be the type of the object throw.

Example:

package quipoin;

public class Exception {
	static int result;

	public static void calculate(int n1, int n2) {
		result = n1 / n2;
	}

	public static void main(String[] args) {
		Exception.calculate(15, 0);
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Exception.calculate(Exception.java:5)
	at Exception.main(Exception.java:10)

In the above example, an exception occurred in line no.10, exception message i.e. by zero, and exception name i.e. java. lang.ArithmeticException.