The Exception Handling is one of the powerful mechanism to handle the java run time exceptions and system errors so that normal flow of the application can be maintained. For Example :
- Run out of memory
- Resource allocation error
- Inability to find file
- Problem in network and database connectivity etc.
For certain exception cases such as resource file is not present in the disk, database connectivity etc. we handle such scenarios by exception handling so that execution of program will not abrupt to terminate. Some times these exceptions(Mostly Use of Custom Exception) can be throw by code also for certain cases.
Will discuss all types of built-in exceptions, errors and custom exception creations and handling in detail in all these below topics.
Main Topics Covered
- Exception Hierarchy?
- What is Exception? Difference between Exception and Error?
- Built-in Exception? Difference between Checked and Unchecked Exception?
- How JVM Handle Exception and Error?
- Exception Handling Keywords
- How to use try, catch, finally,throw and throws?
- Chained Exception
- Custom Exception/User Defined Exception?
- Exception handling with method overriding
- Common Example of Java Exceptions
- [Top 50] Exception Handling Interview Question and Answers
In Java, all exception and errors types are classes and sub classes that implements Throwable interface, which is base for Exception Hierarchy. One branch is headed by Exception and another branch by Error.
All these above exceptions inside java library (java.lang) are also called built-in exception and not required to import exception classes.
The main advantage of exception handling is to maintain the normal flow of the application.
What is Exception?
In Java, an exception is an unwanted or unexpected event which throws during execution of a program at runtime that’s disrupts the normal flow of program instructions.
Exception VS Error
Exception : Exception indicates conditions that a reasonable application might try to catch.
- RuntimeException : Programming Errors that can be detected while testing.
Error: An error indicate irrecoverable serious problem that a reasonable application should not try to catch. Error are used by JVM to indicate errors having to do with JRE.
For Example: OutOfMemoryError, VirtualMachineError , AssertionError, StackOverFlowError etc.
Exceptions further divided in to two as Checked Exception and Unchecked Exception
Checked Exception can be identified at compile time. The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions For Example : ClassNotFoundException, SQLException and RemoteException etc.
Unchecked exception not identified at compile time but they occurred at runtime. All Exceptions which are sub class of RuntimeException are called as Unchecked Exception. For Example: NullPointerException, ArithmaticException and ArrayOutOfBoundException etc.
How JVM Handle Exception and Error?
Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it over to JVM. This exception object contains information like name, description of the exception, and current state of the program where exception has occurred. The process of creating exception object and hand it over to JVM is called throwing an exception. There can be list of methods that called this method where exception occurred . This ordered list of methods are called methods Call Stack Trace. Call Stack. Now steps to handle default exception handling by JVM:
- The run-time system will search the call stack in reverse order to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler (try).
- If it find out any exception handler(try) then it passes the occurred exception to it and check having appropriate handler type matches with thrown exception object to handle.
- If all the methods on call stack searched and couldn’t have found the appropriate handler then run-time system handover the Exception Object to default exception handler. Which is part of JVM. This handler prints the exception information in the following format and terminates program abnormally.
Exception Handling Keywords
Java Exception handling can be managed by five keywords:
|try||The try block governs the statements that are enclosed within it and defines the scope of exception handler associated with it. Try block follows catch or finally or both.|
|catch||The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.|
|finally||when an exception is raised, the statement in the try block is ignored, some times it is necessary to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose.|
|throw||The throw class is used to call exception explicitly. You may want to throw an exception when the user enters a wrong login ID and pass word, you can use throw statement to do so.
The throw statement takes an single argument, which is an Object of exception class.
|throws||The throws statement species the list of exception that has thrown by a method.
If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement.
Below is order and use of keywords in sequence. Will discuss more in detail in below topics.
How to use try, catch, finally, throw and throws?
Below topics will cover syntax and uses of different cases to use try, catch, finally, throw and throws keywords.
- Java try and catch block (Java 7+)
- Java multiple catch block (Java 7+)
- Java nested try
- Java finally block
- Java throw keyword
- Java Exception Propagation
- Java throws keyword
- final vs finally vs finalizefinal vs finally vs finalize
Key Points to Remember
- A method can have more than one statements that might throw exceptions, so put all these statements with in try block and provide separate catch block for each of them to handle exceptions.
- If an exception occurred with in try block that will handle by exception handler catch blocks associated to after try block.
- There can be more than one catch block after try block and each catch block to handle different exception argument type inherits from Throwable interface (Exception or CustomException).
- A finally block is optional and used to cleanup code e.g. closing of file or database connections. Finally block always executed whether exception occurred or not. if exception occurred sequence of block execution will like try, catch and finally. If exception not occurred will execution sequence like try and finally.
- For each try block there can be zero or more catch block, but only one finally block.
In above detail you learn about how JVM throw exceptions and call stack works. In Exception Hierarchy one exception is related with another exception. That’s what in Chained Exception describes cause of another exception by
Throwable(String message, Throwable cause)
Where message is the exception message and cause is the exception that causes the current exception.
For more detail and example follow link Java Chained Exception
Exception Handling with Method Overriding
For exception handling in overriding method created 4 rules based on 4 cases as below:
- If parent-class method doesn’t declare any exception
- If parent-class method declares unchecked exception
- If parent-class method declares checked exception
- If parent-class method declares both checked & unchecked exceptions
Follow this link to handle each case and examples Exception Handling with Method Overriding
Java Custom Exceptions
Here you have see lots of built-in exceptions provided by java library (java.lang). Now you will learn to create and uses of Custom Exception in below link. Custom Exception also called as User Defined Exception.
Common Example of Java Exceptions
Below are some common example where unchecked exception may occurs:
If we divide any number with zero, will throw an exception as ArithmaticException.
int y=0; int x=y/50; //dividing 0 with some value
See complete example :[Solved] java.lang.ArithmeticException: / by zero in JAVA
If we have null reference on any variable, performing any optaion on that variable will throw an exception as NullPointerException.
String str=null; System.out.println(str.length());//performing operation on null reference
See complete example : [Solved] NullPointerException In Java
The wrong formatting of any value can throw an exception as NumberFormatException. Suppose I have string variable that have characters and converting it to Integer by parseInt() will throw an exception as NumberFormatException.
String c="abc"; int x=Integer.parseInt(c);//trying to convert String non digit values to int
See complete example :
If you are assigning any value in wrong index of array, it will throw an exception as ArrayIndexOutOfBoundsException.
int empArr=new int; empArr=200;//throw index out of bound because allow range from 0 to n-1
See complete example : [Solved] ArrayIndexOutOfBoundException in JAVA
You can also check exception handling scenarios from below categories:
Exception Handling Interview Questions and Answers
Here you have learn everything about Java Exception Handling. Now it’s time to crack interview. I have created set of 50 questions which frequently asked over interviews.
You have learn in this tutorial for exception handling hierarchy and handling it. Mainly focused on below topics as below:
- Classification of Exception and errors and their uses.
- Checked and Unchecked Exception
- How JVM internally handle Exception?
- Five key words (try, catch, finally, throw and throws) and uses of it.
- Exception Propagation and Exception Chaining.
- 4 Rules to handle exception in Overriding Method.
- Preparation for Interview.