An exception is thrown whenever an unusual event occurs in Java say for instance there is an incorrect code written it will give an unexpected result.
Whenever an exceptional event occurs, it will create a hindrance to the normal flow of the program.
Exceptional handler is that snippet of code which helps in catching and resolving the exception.
Whenever an exception occurs the process of execution of the program is transferred to an appropriate exception handler.
The try-catch-finally block is used to handle the exceptions.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception and the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block.
All the exceptions are subclasses of java.lang.Exception
.
Throwable is a parent class of all exception classes. There are two types of exceptions:
'Checked exceptions' and 'unchecked exceptions' or 'RunTimeExceptions'. Both type of exceptions extends 'exception' class.
Runtime exception represents the problems that occurs because of a programming problem. Such problems include some of the following :
Arithmetic exceptions : eg. Dividing by zero.
Pointer exceptions : eg. Trying to access an object through a null reference.
Indexing exceptions : eg. Attempting to access an array element through an index that is too large or too small.
Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program and in a typical one there can be numerous. By adding runtime exceptions in every method declaration a program's clarity will get reduced. Thus, the compiler does not require one to catch or specify runtime exceptions (although one can). The solution is to rectify the programming logic wherever the exception has occurred or provide a check.
Checked exceptions forces the programmer to catch them explicitly in try-catch block. It is a subclass of Exception. Example : IOException.
An error is an irrecoverable condition occurring at runtime say for instance 'OutOfMemory' error. These JVM errors cannot be repaired at runtime. Though error can be caught in catch block still the execution of application will come to a halt and is not recoverable.
On the other hand exceptions are conditions that occur because of bad input or human error.
For e.g. 'FileNotFoundException' will be thrown if the specified file does not exist or a 'NullPointerException' will take place if one tries using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)
If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the 'throws' clause at the function declaration.
public void parent() {
try {
child();
}
catch(MyCustomException e){ }
}
public void child throws MyCustomException {
// put some logic so that the exception occurs.
}
'Throw' keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of 'Throwable'.
public void parent() {
try {
child();
}
catch(MyCustomException e) { }
}
public void child{
String iAmMandatory=null;
if(iAmMandatory == null) {
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
A 'ClassNotFoundException' is thrown when the reported class is not found by the 'ClassLoader' in the 'CLASSPATH'. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader. Hence the class from the child classloader is not visible. Consider if 'NoClassDefFoundError' occurs then it would be something like this :
java.lang.NoClassDefFoundError src/com/TestClass But this does not mean that the 'TestClass' class is not in the CLASSPATH. It means that the class 'TestClass' was found by the 'ClassLoader'. However, when one tries to load the class, it runs into an error while reading the class definition. This typically happens when the class in question has static blocks or members which uses a Class that's not found by the ClassLoader. So, in order to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
//1
try{
//lines of code that may throw an exception
}
catch(Exception e){
//lines of code to handle the exception thrown in try block
}
finally{
//the clean code which is executed always no matter the exception occurs or not.
}
//2
try{}
finally{}
//3
try{
}
catch(Exception e){
//lines of code to handle the exception thrown in try block
}
The try block must be always followed by the try block. If there are more than one catch blocks they all must follow each other without any other block in between. The finally block must follow the catch block if one is present. If the catch block is absent the finally block must follow the try block.
If an application can reasonably be expected to recover from an exception then it can be said as a checked exception. If an application cannot do anything to recover from the exception then it is said to be an unchecked exception.
To create one's own exception extend the Exception class or any of its subclasses. Say for instance,
class New1Exception extends Exception { } // this will create Checked Exception
class NewException extends IOExcpetion { } // this will create Checked exception
class NewException extends NullPonterExcpetion { } // this will create UnChecked exception
The 'StackOverFlowError' is an error object thrown by the runtime system when it encounters that the application/code has ran out of the memory. It may occur in case of recursive methods or when a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.
Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value are.
No. Once the control jumps to the catch block it never returns to the try block instead it goes to finally block (if present).
The code is put in a finally block because irrespective of try or catch block execution, the control will flow to finally block. Typically, finally block contains release of connections, closing of result set etc.
No. If the exceptions are siblings in the exception class's hierarchy i.e. if one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.
No. It is not possible to have a try block without catch or finally block as it will result in a compilation error. The try block must be followed by a catch or a finally block. It is acceptable to omit the either of the catch or the finally block but not both of them.
All the exceptions inherit a method 'printStackTrace()' from the 'Throwable' class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.
You can write a single catch block to handle all the exceptions thrown during the program. If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception that occurred. This will also reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.
Yes, a catch block can throw the exception caught by itself which is called as rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException{
try {
//code that may throw the FileNotFoundException
}
catch(FileNotFound eFnf) {
throw FileNotFound();
}
}
Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called as exception matching.
Compilation would fail in this case if the catch block for handling the most specific exceptions is not placed above the catch block written to handle the more general exceptions.
//The code below will not compile.
try {
// code that can throw IOException or its subtypes
}
catch (IOException e) {
// handles IOExceptions and its subtypes
}
catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
// The code below will compile successfully
try {
// code that can throw IOException or its subtypes
}
catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
}
catch (IOException e){
// handle FileNotFoundException only
}
Compilation would fail in this case if the catch block for handling the most specific exceptions is not placed above the catch block written to handle the more general exceptions.
//The code below will not compile.
try {
// code that can throw IOException or its subtypes
}
catch (IOException e) {
// handles IOExceptions and its subtypes
}
catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
// The code below will compile successfully
try {
// code that can throw IOException or its subtypes
}
catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
}
catch (IOException e){
// handle FileNotFoundException only
}
An empty catch block is considered legal by leaving the catch block without writing any actual code to handle the exception caught. e.g. The code below is legal but not appropriate, as in this case you will not get any information about the exception thrown.