If you developing any kind of application using Java. So there are lots of chances to get an exception in your application. To write code exception free and make a standard flow of code java provide a very strong mechanism called Exception handling. So in this tutorial, we are going to focus on what is Exception handling in java with interview questions and answers.
What is an exception in Java?
In Java exception is an event which comes at runtime and an abnormal condition which can interrupt the flow of the application. for example, the arithmetic exception comes when you are going to divide any number by 0.
Exception Handling in Java.
Exception handling processes to handle or manage the exception like an arithmetic exception, class not found or any runtime exception. In Java try{}catch{} block will be used to handle exceptions.
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); try { int c = a / b; System.out.println(c); } catch (Exception e) { System.out.print("Please enter a valid number " + e); } } }
In above code, the risky code is written in the try block handling code is written in the catch block.
Hierarchy of exception handling.
How to Handle Exception in Java.
Using try, catch, finally, throw and throws we handle the Exceptions in Java.
try{} block
try is a block which contains all the risky code. code that might throw an exception will enclose with try{} block. must use try{} block inside a method and must be followed by catch{} or finally{} block.
try{} with catch(Exception){}
public class Main { public static void main(String[] args) { try { // risky code............... } catch (Exception e) { // statement to handle exception } } }
try{} with finally{}
public class Main { public static void main(String[] args) { try { // risky code............... } finally { // statement to handle exception } } }
catch(){} block
In above code, you can see catch block is used to handle the Exception. It must be used after the try block only.You can use multiple catch block with a single try block.
finally{} block
The finally{} block is used to write the code which should be executed whether the exception is handled or not. it is used to write code like closing input-output stream or close database connection which is important in any condition.
In the below code, I try to execute statement “10/0” so there is the exception but with the exception message “finally block is executed” will also print on the console.
public class Main { public static void main(String[] args) { try { // risky code............... System.out.println(10/0); } finally { // statement to handle exception System.out.println("finally block is executed"); } } }
Types of exceptions in Java.
- Checked Exception
- Unchecked Exception
Checked Exception in Java:
Exceptions that are checked at compile time. A checked exception must be caught somewhere in your code. If you invoke a method that throws a checked exception but you don’t catch the checked exception somewhere, your code will not compile. That’s why they’re called checked exceptions. the compiler checks to make sure that they’re handled or declared. following are the example of the checked exception in Java.
- FileNotFoundException
- IOException
- CloneNotSupportedException
- ParseException
- ClassNotFoundException
- NoSuchMethodException
- NoSuchFieldException
- InstantiationException
- InterruptedException
In below code, I try to pass “my.java.User” class Class.forName() but there is no class with this name. So compiler will try to load this class but if class is not available It will throw an exception “ClassNotFoundException”
public class Main { public static void main(String[] args) { try { Class myclass = Class.forName("my.java.User"); System.out.println("Class found successfully!"); } catch (ClassNotFoundException ex) { System.err.println("A ClassNotFoundException was caught: " + ex.getMessage()); ex.printStackTrace(); } } }
Unchecked Exception in Java:
The exception that is checked at runtime is called the unchecked exception. the compiler will not force solve this exception. for example, if you write a program to divide a number there may be user try to divide the number by Zero than there will be an unchecked exception. or you can see the example ArrayIndexOutOfBoundsException.
These are the following unchecked exception in Java.
ArrayIndexOutOfBoundsException
- Unchecked Exception List
- IllegalArgumentException
- IllegalStateException
- ClassCastException
- NullPointerException
- AssertionError
- ExceptionInInitializerError
- NumberFormatException
- NoClassDefFoundError
- StackOverflowError
In below code, we will try to find array index a[n] but array index is valid till a[n-1] and if we try to find a[n] array is out of the index.
import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); } System.out.println(a[n]); // here array index is valid till a[n-1] and if we try to find a[n] array is out of index. } }
Throw and Throws keyword in Java.
Java throw keyword:
throw keyword is used to throw an exception explicitly. mainly used to throw a custom exception. we can define our own exception in java is called the custom exception.
public class Main { static void validate(int age) { if (age < 18) throw new ArithmeticException("User is ot valid for voting"); else System.out.println("User is valid for voting"); } public static void main(String args[]) { validate(15); } }
Java throws keyword:
throws keyword is used to declare an exception. It is used with method signature. A method in which may be the chance to get the exception, the compiler will warn you to handle exception so you can handle that exception by using throws keyword or try catch block for example check below code.
class Main { public static void main(String[] args)throws InterruptedException { Thread.sleep(5000); System.out.println("Hello Geeks"); } }
In the above code sleep() method might throw an Interrupted Exception. so the compiler will force to handle this exception using try-catch block or we can use throws. if we are going to use throws then JVM will handle it.
How to create the custom exception in Java.
class MyException extends Exception{ public MyException(String s) { super(s); } } class Main { public static void main(String[] args)throws MyException { throw new MyException("Custom Exception"); } }
In above code, we create a custom exception “MyException”.
Some important point about exception handling in Java you should remember.
- Try block must be followed by catch block or finally block.
- Error and exceptions are different things.
- We can define our own exception by extending Exception class.
- All exception classes are subtypes of the java.lang.Exception class.
- finally block will be executed in every condition but catch blocks depend on conditions.
- throw and throws are the keywords in Java.
Java exception handling interview questions and answers
How can you catch multiple exceptions?
By using multiple catch block.
try { // ... } catch (FileNotFoundException ex) { // ... } catch (EOFException ex) { // ... }
What is the difference between a checked and an unchecked exception?
Checked exceptions come at the time of compilation and the unchecked exception has come at runtime.
What is Error?
An Error “indicates serious problems that a reasonable application should not try to catch.”The error is something that most of the time you cannot handle it.
What is the difference between exception and error in java?
Errors are mainly caused by the environment in which an application is running. For example, OutOfMemoryError happens when JVM runs out of memory. exceptions are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access the null object or arrayOutOfIndex.
What is StackOverflowError in java?
StackOverflowError is an error which is thrown by the JVM when stack overflows.
Give some examples of checked exceptions and unchecked exceptions?
Checked: IOException, SQLException, ClassNotFoundException.
unchecked: NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException.
What is the use of printStackTrace() method?
printStackTrace() method is used to print the detailed information about the exception occurred.