InterviewSolution
| 1. |
Java Exception Handling |
||||||||||||||||||||||||||||||||||||||
|
Answer» Meaning of Exception: An exception is an unwelcome or unexpected occurrence that occurs during the execution of a program, i.e. at run time, and disturbs the program's usual flow of instructions. Error vs Exception: What is the Difference? An error implies that there is a major problem that a reasonable programme should not attempt to solve whereas an exception denotes a set of circumstances that a reasonable programme would attempt to catch. Hierarchy of Exceptions: As we can see in the above image, all exception and error kinds are subclasses of the hierarchy's root class, Throwable. Exceptions can be divided into two categories:
Built-in Exceptions in Java: Exceptions that are present in Java libraries are known as built-in exceptions. The following table lists the built-in exceptions in Java:
Java Try-Catch:-
try { // code to be checked }
catch { // code to handle exception } finally keyword:- In Java, the finally block represents code that is to be executed whether or not an exception is caught. In case a catch block is present after the try block, it is run after the catch block has been executed. However, in case there is no catch block present after the try block, the finally block is executed after the try block has been executed. Syntax - finally{ // code to be executed } Difference between final, finally and finalize: The following table lists the differences between final, finally and finalize:
throw keyword:- In Java, the throw keyword is used to throw an exception from a method or any block of code. We can either throw a checked or an unchecked exception. Throwing custom exceptions is the most common use of the throw keyword. throws keyword:- The throws keyword is used to handle exceptions in the absence of a try/catch block. It specifies the exceptions that a method should throw in case an exception occurs. Example - class Test {// This method throws an exception static void foo() throws IllegalAccessException { System.out.println("Inside the foo() method"); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { foo(); } catch (IllegalAccessException e) { System.out.println("Exception caught"); } } } Output - Inside the foo() methodException caught Explanation - In the above code, the function foo() specifies that an IllegalAccessException should be thrown in case an exception occurs using the throws keyword. In the foo() function, we explicitly throw an exception. This is caught by the catch block present in the main method of the class. |
|||||||||||||||||||||||||||||||||||||||