Java exception is an object which is created at the run time due to some error present in the piece of code.Whenever an exceptional condition occurs an object is created and it is thrown in the method that caused the error . The method may handle the object or pass it on.This objects are caught by another method and processed.The main cause behind the generation of exception(object) is due to syntactical error in the piece of code.It can also arise due to the violation of user defined condition in the program.
Java exception handling is nothing but a way to deal with the run time errors and how they can be corrected or skipped depending upon users choice.Exception handling is done with the help of five keywords try,catch,throw,throws and finally.
1.try - This keyword is used to check whether a block of code contains exception or not.
try{
//code;
}
2. catch - If java finds any exception in the try block then it stops there itself and dose not executes further. Java shows an error message at the run time, so instead of getting compilers message we can use catch keyword to show our own message for making our program more user friendly.
try{
//code;
}catch(exception_type reference){
//code;
}
3. throw - system generated exception are automatically thrown by java run time sytem. To do this manually , throw keyword is used.
throw throwable_instance;
4. throws - Any exception thrown out of a method is specified with the help of throws clause.
type method_name(parameter_list) throws eception_type{
//code;
}
5. finally - Any code written under the finally is executed after the try block is over.It does not depends upon the exception present in the try block.
try{
//code;
}catch(exception_type reference){
//code;
}
finally{
//code;
}
example
import java.io.*;
//demonstrate multicatch system
class catch1 {
public static void main(String arg[]){
try{
int a = arg.length;
System.out.println("a =" +a);
int b = 42/a;
int c[] = {1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println("divide c by 0:" + e);
} catch(Exception e){
System.out.println("array index oob : "+ e);
}
System.out.println("after try/catch blocks.");
}
}
explaination :Here we have created a class named as catch1 in which we have defined a static main class. The main method has a try block code contains two types of exception(error), (i) ArithemeticException and, (ii) ArrayOutOfBoundException . There are two catch blocks which will catch the two exceptions, the first one will catch ArithemeticException and the second will catch all kinds of exception(error) as "Exception"(class name) is the base class for all run time exception generated.
We have discussed about try and catch keyword , now lets deal with the other three keywords throw , throws and finally.
throw
Till now we were catching the exception at the run time. We can also throw exception explicitly from our program, with the help of throw keyword.
syntax
throw Throwable_instance;
throwable_instance is an object of type throwable class or sub-class of throwable.Primitive types like int , char and non-Throwable classes , such as string and object,cannot be used as exception.
There are two ways of creating a throwable object either by passing as a reference in the parameter of catch statement or with the help of new operator.
class demo{
static void call(){
try
{
throw new ArithmeticException("error"); //created a instance of type throwable
}catch(ArithmeticException e){
System.out.println("error found in call()");
throw e; //rethrow the exception as a reference
}
}
public static void main(String args[]){
try{
call();
}catch(ArithmeticException e){
System.out.print("recaught :" + e);
}
}
}
Explaination :In the above program , we are handling the Arithmetic type exception in two ways , first in the call() method and second in the main() method.call() method has a try block in which a instance is generated of type ArithmeticException , and then it is thrown . The catch block in the call() method catches the Exception and then it enters the catch block for its execution, here in the catch block it is again the reference of ArithmeticException is thrown. Now in second case i.e in the main() method the call() method is being called within try block, and then it is passed to the catch block as normal try and catch.
The reference "e" thrown in the catch block of call() method creates another exception in the try block of main() method , then it is handled by the respective catch block giving "recaught : error" as output. "error" was passed as a argument in the ArithmeticException type instance.
throws
It is a kind of passing message to the caller of a function that a specific type of message can be generated by the called method , which the called method does not handle. So the callers can take care of the exception and proceed further. syntactically this throws clause is defined with the method declaration statement.
type method_name(parameter list) throws exception list{
//body of method;
}
Here exception list is a comma separated list of the exceptions that a method can throw.
finally
We know that exception causes abrupt execution of a program i.e whenever java finds any kind of exception it stops execution there itself . This can create problem in many cases.Let us take an example of a record file , you can perform many functions on it like update , delete etc. but at the end you have to close this file. In java if it finds any exception in the try block of deletion code it will throw that exception and stop , but your file remains open .The opened file need to be closed before proceeding further.This type of problems can be solved with the help of finally keyword.
finally keyword creates a block of code that will be executed after a try/catch block has completed and before the code following the try and catch block.The finally block will execute whether or not an exception is thrown.If an exception is thrown , the finally block will execute even if or not the catch block excepton matches with the thrown exception.However , finally block is optional and it does not delay the execution tome. It returns with the completion of try/catch block.
// demonstrate finally
class FinallyDemo{
static void procA(){
try{
System.out.println("inside procA");
throw new RuntimeException("demo");
}finally{
System.out.println("procA's finally");
}
}
static void procB(){
try{
System.out.println("inside procB");
return;
}finally{
System.out.println("procB's finally");
}
}
static void procC(){
try{
System.out.println("inside procC");
}finally{
System.out.println("procC's finally");
}
}
public static void main(String args[]){
try{
procA();
}catch(Exception e){
system.out.println("Exception caught");
}
procB();
procC();
}
}
Types of Exception
All the exception types are subclass of the built in class THROWABLE. Throwable is then sub classed into two distinct types i.e exception and error. The exception class is used for exceptional conditions that user should catch. There is an important subclass of exception called RuntimeException.Exception of this types are automatically defined for the program that we write and include things such as division by zero and array indexing.
Error is the second sub class of the throwable class, which defines exception that are not expected to be caught at normal circumstances by our program.Exception of type Error are used by the java run-time system to indicate errors having to di with the run-time environment itself.Stack overflow is an example of such an error.
Java built in exception are divided into two i.e. checked exception and unchecked exception.
checked exception are the compile time exception , i.e. the compiler forces us to handle this exception. eg: IOException
unchecked exception are those that are not forced by the compiler to handle the exception. eg : ArithmeticException.
Java exception handling is nothing but a way to deal with the run time errors and how they can be corrected or skipped depending upon users choice.Exception handling is done with the help of five keywords try,catch,throw,throws and finally.
1.try - This keyword is used to check whether a block of code contains exception or not.
try{
//code;
}
2. catch - If java finds any exception in the try block then it stops there itself and dose not executes further. Java shows an error message at the run time, so instead of getting compilers message we can use catch keyword to show our own message for making our program more user friendly.
try{
//code;
}catch(exception_type reference){
//code;
}
3. throw - system generated exception are automatically thrown by java run time sytem. To do this manually , throw keyword is used.
throw throwable_instance;
4. throws - Any exception thrown out of a method is specified with the help of throws clause.
type method_name(parameter_list) throws eception_type{
//code;
}
5. finally - Any code written under the finally is executed after the try block is over.It does not depends upon the exception present in the try block.
try{
//code;
}catch(exception_type reference){
//code;
}
finally{
//code;
}
example
import java.io.*;
//demonstrate multicatch system
class catch1 {
public static void main(String arg[]){
try{
int a = arg.length;
System.out.println("a =" +a);
int b = 42/a;
int c[] = {1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println("divide c by 0:" + e);
} catch(Exception e){
System.out.println("array index oob : "+ e);
}
System.out.println("after try/catch blocks.");
}
}
explaination :Here we have created a class named as catch1 in which we have defined a static main class. The main method has a try block code contains two types of exception(error), (i) ArithemeticException and, (ii) ArrayOutOfBoundException . There are two catch blocks which will catch the two exceptions, the first one will catch ArithemeticException and the second will catch all kinds of exception(error) as "Exception"(class name) is the base class for all run time exception generated.
We have discussed about try and catch keyword , now lets deal with the other three keywords throw , throws and finally.
throw
Till now we were catching the exception at the run time. We can also throw exception explicitly from our program, with the help of throw keyword.
syntax
throw Throwable_instance;
throwable_instance is an object of type throwable class or sub-class of throwable.Primitive types like int , char and non-Throwable classes , such as string and object,cannot be used as exception.
There are two ways of creating a throwable object either by passing as a reference in the parameter of catch statement or with the help of new operator.
class demo{
static void call(){
try
{
throw new ArithmeticException("error"); //created a instance of type throwable
}catch(ArithmeticException e){
System.out.println("error found in call()");
throw e; //rethrow the exception as a reference
}
}
public static void main(String args[]){
try{
call();
}catch(ArithmeticException e){
System.out.print("recaught :" + e);
}
}
}
Explaination :In the above program , we are handling the Arithmetic type exception in two ways , first in the call() method and second in the main() method.call() method has a try block in which a instance is generated of type ArithmeticException , and then it is thrown . The catch block in the call() method catches the Exception and then it enters the catch block for its execution, here in the catch block it is again the reference of ArithmeticException is thrown. Now in second case i.e in the main() method the call() method is being called within try block, and then it is passed to the catch block as normal try and catch.
The reference "e" thrown in the catch block of call() method creates another exception in the try block of main() method , then it is handled by the respective catch block giving "recaught : error" as output. "error" was passed as a argument in the ArithmeticException type instance.
throws
It is a kind of passing message to the caller of a function that a specific type of message can be generated by the called method , which the called method does not handle. So the callers can take care of the exception and proceed further. syntactically this throws clause is defined with the method declaration statement.
type method_name(parameter list) throws exception list{
//body of method;
}
Here exception list is a comma separated list of the exceptions that a method can throw.
finally
We know that exception causes abrupt execution of a program i.e whenever java finds any kind of exception it stops execution there itself . This can create problem in many cases.Let us take an example of a record file , you can perform many functions on it like update , delete etc. but at the end you have to close this file. In java if it finds any exception in the try block of deletion code it will throw that exception and stop , but your file remains open .The opened file need to be closed before proceeding further.This type of problems can be solved with the help of finally keyword.
finally keyword creates a block of code that will be executed after a try/catch block has completed and before the code following the try and catch block.The finally block will execute whether or not an exception is thrown.If an exception is thrown , the finally block will execute even if or not the catch block excepton matches with the thrown exception.However , finally block is optional and it does not delay the execution tome. It returns with the completion of try/catch block.
// demonstrate finally
class FinallyDemo{
static void procA(){
try{
System.out.println("inside procA");
throw new RuntimeException("demo");
}finally{
System.out.println("procA's finally");
}
}
static void procB(){
try{
System.out.println("inside procB");
return;
}finally{
System.out.println("procB's finally");
}
}
static void procC(){
try{
System.out.println("inside procC");
}finally{
System.out.println("procC's finally");
}
}
public static void main(String args[]){
try{
procA();
}catch(Exception e){
system.out.println("Exception caught");
}
procB();
procC();
}
}
Types of Exception
All the exception types are subclass of the built in class THROWABLE. Throwable is then sub classed into two distinct types i.e exception and error. The exception class is used for exceptional conditions that user should catch. There is an important subclass of exception called RuntimeException.Exception of this types are automatically defined for the program that we write and include things such as division by zero and array indexing.
Error is the second sub class of the throwable class, which defines exception that are not expected to be caught at normal circumstances by our program.Exception of type Error are used by the java run-time system to indicate errors having to di with the run-time environment itself.Stack overflow is an example of such an error.
Java built in exception are divided into two i.e. checked exception and unchecked exception.
checked exception are the compile time exception , i.e. the compiler forces us to handle this exception. eg: IOException
unchecked exception are those that are not forced by the compiler to handle the exception. eg : ArithmeticException.
No comments:
Post a Comment