Exception Handling In Java : Top most Conclusion on Exception handling
One of the most important topic in Java is Exception handling, as we know Programming is buddy task and to handle exception Java Provide by default mechanism called Exception handling .it is also one of the hot topic in interviews whether you are Fresher or experience one exception handling is one of most important topic of the interviewer so guys take a look of my new blog post on Exception handling if you havea ny Question Please comment below..
Exception Handling is the mechanism to handle runtime errors. We need to handle such exceptions to prevent abrupt termination of program.
A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc
What is exception ??
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime
The code that's responsible for doing something about the exception is called an exception handler.
What is exception handling ??
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario.
statement 1;
statement 2;
statement 3; //exception occurs
statement 4;
statement 5;.
statement 2;
statement 3; //exception occurs
statement 4;
statement 5;.
Suppose there is 5 statements in your program and there occurs an exception at statement 3, rest of the code will not be executed i.e. statement 4 and 5 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.
Exception class Hierarchy:
- All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.
Throwable -> Exception -> RuntimeException
- Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes.
- RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs.
Exception are categorized into 3 category:
1) Checked Exception (Compile-time)
The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.
1. Using equals() method:
equals() method compares two strings for equality. Its general syntax is,
2) Unchecked Exception (Run-time)
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.
3) Error
Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow occurs, an error will arise. This type of error is not possible handle in code.
2. try-catch
Java Exception Handling Keywords.
There are 5 keywords used in java exception handling.
1) try
2) catch
3) finally
4) throw
5) throws.
2) catch
3) finally
4) throw
5) throws.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch.
try {
//code that may throw exception
} catch(Exception_class_Name ref){
// Handle exception
}
//code that may throw exception
} catch(Exception_class_Name ref){
// Handle exception
}
Syntax of try-finally block.
try {
//code that may throw exception
} finally {
// code to excecute anyhow
}
//code that may throw exception
} finally {
// code to excecute anyhow
}
Java catch block
Java 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.
Example using Try and catch
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output :
Divided by zero
After exception is handled
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line "After exception is handled" is printed.
Multiple catch blocks
A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.
Example for Multiple Catch blocks.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
catch(Exception ex)
{
System.out.println("any other exception");
}
}
}
Output : divide by zero
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
catch(Exception ex)
{
System.out.println("any other exception");
}
}
}
Output : divide by zero
NOTE: At a time only one Exception is occured and at a time only one catch block is executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that exception sub classes inside catch must come before any of their super classes otherwise it will lead to compile time error.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}
Output : Compile-time error
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}
Output : Compile-time error
NOTE: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.
Java Programming & Examples. Get More Example from
https://play.google.com/store/apps/details?id=com.nilstechsys.javaprogrammingexample
https://play.google.com/store/apps/details?id=com.nilstechsys.javaprogrammingexample
Nested try statement
try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catch handler for a particular exception then the outer try is checked for match.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Important points to Remember
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Important points to Remember
1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
2. Super class Throwable overrides toString() function, to display error message in form of string.
3. While using multiple catch block, always make sure that exception subclasses comes before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not and appears at the end of try or catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Output :
Out of try
finally is always executed.
Exception in thread main java.lang.ArrayIndexOutOfBoundException: 3
Out of try
finally is always executed.
Exception in thread main java.lang.ArrayIndexOutOfBoundException: 3
NOTE : For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
Try with Resource Statement
JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.
Syntax:
try ( resource-specification )
{
//use the resource
} catch( ){
...
}
{
//use the resource
} catch( ){
...
}
This try statement contains a paranthesis in which one or more resources is declare. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement, you do not have to explicitly close the resources.
Example without using try with Resource Statement.
import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();//closing BufferedReader stream
} catch(IOException ie){
System.out.println("exception");
}
}
}
Example using try with Resource Statement.
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();//closing BufferedReader stream
} catch(IOException ie){
System.out.println("exception");
}
}
}
Example using try with Resource Statement.
import java.io.*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
} catch(IOException ie){
System.out.println("exception");
}
}
}
NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
} catch(IOException ie){
System.out.println("exception");
}
}
}
NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.
The Java throw keyword is used to explicitly throw an exception.Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
Syntax:
throw ThrowableInstance
Creating Instance of Throwable class:
There are two possible ways to get an instance of class Throwable,
1. Using a parameter in catch block..
2. Creating instance with new operator.
5. Only the object of Throwable class or its subclasses can be thrown.
new NullPointerException("test");
Example demonstrating throw Keyword
class HelloWorld
{
static void validate(int age)
{
if(age < 18)
{
try
{
throw new ArithmeticException("NOT Valid");
}
catch(ArithmeticException e)
{
System.out.println("Age Invalid Exception Caught");
}
}
else
{
System.out.println("Welcome to vote");
}
}
{
static void validate(int age)
{
if(age < 18)
{
try
{
throw new ArithmeticException("NOT Valid");
}
catch(ArithmeticException e)
{
System.out.println("Age Invalid Exception Caught");
}
}
else
{
System.out.println("Welcome to vote");
}
}
public static void main(String args[])
{
validate(13);
}
}
Output : Age Invalid Exception Caught
In the above example the validate() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.
{
validate(13);
}
}
Output : Age Invalid Exception Caught
In the above example the validate() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.
Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.
Syntax :
return_type method_name ( parameter_list ) throws exception_list
{
//definition of method
}
{
//definition of method
}
NOTE : It is necessary for CheckedExceptions (Compile-time) and not necessary for RuntimeException (Run-time) and Error, or any of their subclass.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.
There are two cases:
1. Case 1 : You caught the exception i.e. handle the exception using try/catch.
2. Case 2 : You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
class test{
void method()throws IOException{
throw new IOException("device error"); //checked exception
}
}
public class Testthrows{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("Exception handled");}
}
}
Output: Exception handled
Case2: You declare the exception
void method()throws IOException{
throw new IOException("device error"); //checked exception
}
}
public class Testthrows{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("Exception handled");}
}
}
Output: Exception handled
Case2: You declare the exception
A) In case you declare the exception, if exception does not occur, the code will be executed fine.
B) In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.
class test{
void method()throws IOException{
System.out.println("Device Operation Performed");
}
}
class Testthrows{
public static void main(String args[]) throws IOException{ //declare exception
M m=new M();
m.method();
}
}
void method()throws IOException{
System.out.println("Device Operation Performed");
}
}
class Testthrows{
public static void main(String args[]) throws IOException{ //declare exception
M m=new M();
m.method();
}
}
Output :
A) Device Operation Performed
B) Runtime Exception
NOTE : If you are calling a method that declares an exception, you must either caught or declare the exception.
A) Device Operation Performed
B) Runtime Exception
NOTE : If you are calling a method that declares an exception, you must either caught or declare the exception.
Difference between throw and throws in Java:
throw throws
Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance.Throws is followed by class.
Throw is used within the method.Throws is used with the method signature.
You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance.Throws is followed by class.
Throw is used within the method.Throws is used with the method signature.
You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
No comments:
Post a Comment