Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15
Exception Handling in Java
Exception Handling in Java
• The Exception Handling in Java is one of the
powerful mechanism to handle the runtime errors. • Exceptions can be generated by the Java run-time system, or they can be manually generated by our code. • such as ClassNotFoundException, • IOException, • SQLException, • RemoteException, etc. Types of Exception Java exception handling is managed using five keywords: • try: A suspected code segment is kept inside try block. • catch: The remedy is written within catch block. • throw: Whenever run-time error occurs, the code must throw an exception. • throws: If a method cannot handle any exception by its own and some subsequent methods --needs to handle them, then a method can be specified with throws keyword with its declaration. • finally: block should contain the code to be executed after finishing try and catch block. • A chained exception is created using one of the constructors of the exception class. Throwable Class • Throwable(Throwable cause): A Java constructor creates a new exception object with a specified cause exception. • Throwable(String desc, Throwable cause): A Java constructor creates a new Throwable object with a message and a cause. It allows for chaining exceptions and providing more detailed information about errors. • Throwable class methods enable chained exceptions: • getCause(): It is a Java method of the Throwable class that returns the cause of the current Exception. It allows for accessing the Exception or error that triggered the current Exception to be thrown. • initCause() method: determines the reason for the calling Example of Chained Exception: Filename: ChainedExceptionExample.java public class ChainedExceptionExample { public static void main(String[] args) { try { String s = null; int num = Integer.parseInt(s); // the line will throw a NumberFormatExcepti on } catch (NumberFormatException e) { // create a new RuntimeException with the message "Exception." RuntimeException ex = new RuntimeException("Exception"); // set the cause of the new Exception to a new NullPointerException with t he message " It is actual cause of the exception " ex.initCause(new NullPointerException("It is actual cause of the exception" )); // throw the new Exception with the chained Exception throw ex; } } } O/P • Exception in thread "main" java.lang.RuntimeException: Exception at ChainedExceptionExample.main(ChainedExcep tionExample.java:7) Caused by: Java.lang.NullPointerException: It is actual cause of the exception at ChainedExceptionExample.main(ChainedExcep tionExample.java:8)