Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Saturday, 10 January 2015

Exception Handling with Method Overriding


There are many rules if we talk about methodoverriding with exception handling. Which are given below

1. If the superclass method does not declare an exception:

If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.

2. If the superclass method declares an exception

If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.

1. If the superclass method does not declare an exception:

Case 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
For Example:

import java.io.*;
class Test{
void display(){System.out.println("this is super class");}
}
class Student extends Test{
void display()throws IOException{
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
t.display();
 }
}

Output: Compile Time Error

Case 2: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception  but can declare unchecked exception.
For Example:

import java.io.*;
class Test{
void display(){System.out.println("this is super class");}
}
class Student extends Test{
void display()throws ArithmeticException{
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
t.display();
  }
}

Output: this is subclass

2. If the superclass method declares an exception

Case 1. If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception  but cannot declare parent exception.

Example in case subclass overridden method declares parent exception:

import java.io.*;
class Test{
void display() throws ArithmeticException
{
System.out.println("this is super class");
}
}
class Student extends Test{
void display()throws Exception{
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
try{
t.display();
}
catch(Exception ex) { }
  }
}

Output: Compile Time Error

Example in case subclass overridden method declares same exception

import java.io.*;
class Test{
void display() throws Exception
{
System.out.println("this is super class");
}
}
class Student extends Test{
void display()throws Exception{
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
try{
t.display();
}
catch(Exception ex) { }
  }
}

Output: this is subclass

Example in case subclass overridden method declares subclass exception:

import java.io.*;
class Test{
void display() throws Exception
{
System.out.println("this is super class");
}
}
class Student extends Test{
void display()throws ArithmeticException{
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
try{
t.display();
}
catch(Exception ex) { }
  }
}

Output: this is subclass

Example in case subclass overridden method declares no exception:

import java.io.*;
class Test{
void display() throws Exception
{
System.out.println("this is super class");
}
}
class Student extends Test{
void display() {
System.out.println("this is subclass");
}
publi static void main(String []args){
Test t=new Student();
try{
t.display();
}
catch(Exception ex) { }
  }
}

Output: this is subclass






What is throws keyword in Java

throws keyword:

The throws keyword is used to declare an exception.It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow of the code can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException,ArithmeticException  it is programmers fault so  we  can't  check up before the code being used.

Syntax of throws keyword:

void method_name() throws exception_class_name {
...
}

Which type of  exception should we declare ?

checked exception only, because:
unchecked Exception: under programmer control so programmer can correct the code.
error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or
StackOverflowError.
checked exception: depends on other vendors such as  SQLException,  IOException, FileNotFoundException etc.

Advantage of throws keyword:

Now Checked Exception can be propagated (forwarded in call stack of different methods).

Example which show how checked exceptions can be propagated by throws keyword.

In this example,we are going to see that checked exception also propagates if method declares an exception (i.e. specifies throws keyword with the exception class).

import java.io.IOException;

class Test{
void getFile() throws IOException{
throw new IOException("IO Exception may occur"); //checked exception
}
void display() throws IOException{
getFile();
}
void show(){
try{
display();
}catch(Exception e) { System.out.println("exception handled"); }
}
public static void main(String []args){
Test t1=new Test();
t1.show();
System.out.println("normal flow of the program");
 }
}

Output: exception handled
normal flow of the program

Note: If you are calling a method that declares an exception, you must either caught or declare the exception.

There may be two cases of that:
>1. You caught the exception i.e. handle the exception by try/catch block.
>2. You declare the exception i.e. declare the exception by throws with the method.

>1. You handle the exception:

In case you handle the exception,the code will be executed fine whether exception occurs during the program or not.

import java.io.*;

class Student{
void getFile() throws IOException{
throw new IOException("IO exception may occur");
}
}
class Test{
public static void main(String []args){
try{
Student st=new Student();
st.getFile();
}
catch(Exception e) { System.out.println("exception handled"); }
System.out.println("normal flow of  code");
 }
}

Output: exception handled
normal flow of code

>2. You declare the exception:

In this case there are two case.
1. In case you declare the exception, if exception does not occur, the code will be executed fine.
2. In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.

1. Example of program  declaring the exception if exception does not occur in the method which declares an exception:

import java.io.*;

class Student{
void display()throws IOException{
System.out.println("IO Exception may occur");
}
}
class Test{
public static void main(String []args)throws IOException {  //declare exception here
Student st=new Student();
st.display();
System.out.println("normal flow of code");
}
}

Output: IO exception may occur
normal flow of  code

2. Example of program declaring the exception if exception occurs in the method which declares an exception:

import java.io.*;

class Student{
void display()throws IOException{
throw new IOException("IO exception may occur");
}
}
class Test{
public static void main(String []args)throws IOException  { //declare exception here
Student st=new Student();
st.display();
System.out.println("normal flow of code");
}
}

Output: Exception in thread "main" java.io.IOException: IO exception may occur

Can we rethrow an exception ?

Yes, by throwing same exception in catch block.


What is the difference between throw and throws keyword:

                     throw                                                                   throws
1. throw is used to explicitly throw an exception.      1. throws is used to declare an exception.
2. checked exception can not be propagated .            2. checked exception can be propagated                        without throws.                                                           with throws.
3. throw is followed by an instance.                           3. throws is followed by class.
4. throw is used within the method.                           4.  throws is used with the method signature.
5. You cannot throw multiple exception                    5. You can declare multiple exception e.g.
                                                                                         public void method()throws
                                                                                         IOException,SQLException.

Next>> Exception Handling with Method Overriding



Friday, 9 January 2015

What is throw and throws keyword in Java

throw keyword:

The throw keyword is used to explictily throw an exception.We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception.

Example of throw keyword:

In this example, we have created the checkAge method that takes integer value as a parameter.If the age is less than 18, we are throwing the ArithmeticException otherwise print a message You are not minor.

class Test{
static void checkAge(int age){
if(age<18)
{
throw new ArithmeticException("you are minor");
}
else {
System.out.println("you are not minor");
}
}
public static void main(String []args){
checkAge(15);
System.out.println("rest of the code");
}
}

Output: 
Exception in thread main java.lang.ArithmeticException:you are minor  //if age=15
you are not minor  //if age=20
rest of the code

Custom Exception :

If you are creating your own Exception that is known as custom exception or user-defined exception.

For Example:

save as  InvalidAgeException.java
class InvalidAgeException extends Exception{
InvalidAgeException(String s){

 }
}

save as  Test.java
class Test{
static void checkAge(int age) throws InvalidAgeException {
if(age<18)
throw new InvalidAgeException("you are minor");
else
System.out.println("you are not minor");
}
public static void main(String []args){
try{
checkAge(15);
}catch(Exception ex){
System.out.println("Exception occured... "+ex);
}
System.out.println("rest of the code");
 }
}

Output: Exception occured... InvalidAgeException:you are minor
rest of the code

What is Exception Propagation in Java

Exception propagation(forwarding):

An exception is first thrown from the top of the stack and if it is not caught,it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method,and so on until they are caught or until they reach the very bottom of the call stack.
This is called exception propagation(forwarding).

Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Example of Exception Propagation

class Test{
void divide(){
int data=50/0;
}
void display(){
divide();
}
void run(){
try{
display();
}
catch(Exception e){
System.out.println("exception is handled"); }
}
public static void main(String []args){
Test t1=new Test();
t1.run();
System.out.println("normal flow");
}
}

Output: exception is handled
normal flow

In the above example exception occurs in divide() method where it is not handled,so it is propagated to previous display() method where it is not handled, again it is propagated to divide() method where exception is handled.Exception can be handled in any method in call stack either in main() method,run() method,display()  method or divide() method.

Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).

For Example:

class Test{
void divide(){
throw new java.io.IOException("IO Exception occur");  //checked exception
}
void display(){
divide();
}
void run(){
try{
display();
}
catch(Exception e){
System.out.println("exception is handled"); }
}
public static void main(String []args){
Test t1=new Test();
t1.run();
System.out.println("normal flow");
}
}

Output: Compile Time Error

What is Nested try block in Java

Nested try block:

try block within a try block is known as nested try block.

Why use nested try block used and where ?

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error.
In such cases, exception handlers have to used nested try block.

Syntax:
......
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
 {

  }
}
catch(Exception e)
{

}
......

For Example:

class Test{
public static void main(String []args){
try{
   try{
     System.out.println("going to divide by zero");
int x =25/0;
}
catch(ArithmeticException ex) {
System.out.println(ex);
}
try{
int y[]=new int[10];
y[12]=8;
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println(ex);
}
System.out.println("other statement");
}  // end of outer try bock
catch(Exception ex){
System.out.println("Exception handled");
}  // end of outer catch bock
System.out.println("normal flow");
 }
}

Output: going to divide by zero
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 12
other statement
normal flow


finally block:

The finally block is a block that is always executed.It is mainly used to perform some important tasks such as closing connection, file,stream,transaction etc.

Note:Before terminating the program, JVM executes finally block(if any).

Note:finally must be followed by either try or catch block.

Why use finally block ?

finally block can be used to put "cleanup" code such as closing a file,closing connection etc.

Examples of the finally block

>1. Program in case exception does not occur

class Test{
public static void main(String [])args{
try{
int a=40/4;
System.out.println(a);
}
catch(NullPointerException ex){
System.out.println(ex);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
 }
}

Output:  10
finally block is always executed
rest of the code

>2. Program in case exception occured but not handled

class Test{
public static void main(String []args){
try{
int a=15/0;
System.out.println(a);
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
 }
}

Output: finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

>3. Program in case exception occured and handled

class Test{
public static void main(String []args){
try{
int data=15/0;
System.out.println(a);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally { System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
}
}

Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code

Note: For each try block there must 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).

Next>> What is throw and throws keyword in Java

Thursday, 8 January 2015

Multiple catch block in Exception Handling in java

Multiple catch block in Exception Handling:

If you have to perform different tasks at the occrence of different Exceptions,you have to use multple catch blocks.

For Example:  

class Test{
public static void main(String []args){
try{
int x[]=new int[5];
x[5]=20/0;
}
catch(ArithmeticException ex) {  System.out.println("task1 is completed");  }
catch(ArrayIndexOutOfBoundsException ex) {  System.out.println("task 2 completed");   }
catch(Exception ex) {  System.out.println("common task completed");  }
System.out.println("rest of the code.....");
 }
}

Output: task1 completed
rest of the code.....

Note: At a time only one Exception is occured and at a time only one catch block is executed.

Note: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.

Explanation: Suppose you want to catch ArithmeticException, then first use ArithmeticException in catch block then Exception.
i.e. catch( ArithmeticException ex) { }
     catch( Exception ex) { }

Note: If you don't fallow these rules then Compile-time error would occure.

For Example:

class Test{
public static void main(String []args){
try{
int x[]=new int[10];
x[12]=20/0;
}
catch(Exception e)  {System.out.println("common task completed");  }
catch(ArithmeticException e)  {System.out.println("task1 is completed");  }
catch(ArrayIndexOutOfBoundsException e)  {System.out.println("task 2 completed");  }
System.out.println("rest of the code...");
 }
}

Output: Compile-time error

Next>> What is Nested try block in Java

What is Exception Handling in Java

Exception Handling:

The exception handling is one of the powerful mechanism provided in java.It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained.

The Dictionary Meaning of  Exception is an abnormal condition.
In java ,exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Note: Exception Handling is a mechanism to handle runtime exceptions and errors.

Advantage of Exception Handling:

The main advantage of exception handling is that normal flow of the application is maintained Exception normally disrupts the normal flow of the  application that is why we use exception handling.

Suppose there are 20 lines in your program and there occurs an exception at line 8, rest of the code will not be excecuted i.e. statement 9 to 20 will not run.If we perform exception handling, rest of the exception will be executed.That is why we use exception handling.

Types of Exception:

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception.
The according to sun microsystem there are three types of exceptions in java:

1. Checked Exception
2. Unchecked Exception
3. Error

Note: Throwable class is the super class of Exception.

What is the difference between checked and unchecked exceptions ?

>1.Checked Exception:

The classes that extend Throwable class except RuntimeException class and Error are known as checked exceptions e.g.IOException, ServletException, FileNotFoundException, SQLException etc. Checked exceptions are checked at compile-time.

>2.Unchecked Exception

The classes that extend RuntimeException class are known as unchecked exceptions e.g. ArithmeticException,NumberFormatException,NullPointerException,ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

>3.Error

Error is an irrecoverable(that can not be recoverable) e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may occur:

There are given some scenarios where unchecked exceptions can occur. They are given below:

1. ArithmeticException occurs scenarios :

If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;  //ArithmeticException

2. NullPointerException occurs scenarios 

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
String s1=null;
System.out.println(s1.length());  //NullPointerException

3. NumberFormatException occurs scenarios 

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.

String s1="xyz";
int a=Integer.parseInt(s1);  //NumberFormatException

4. ArrayIndexOutOfBoundsException occurs scenarios

If you are inserting any value at wrong index position in Array, it would result ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[10];
a[12]=20;  //ArrayIndexOutOfBoundsException


Next>> Exception Handling using try and catch

Exception handling using try catch block in java

Exception handling using try-catch block :

There are five keywords used in Exception handling

1. try
2. catch
3. finally
4. throw
5. throws

try block:

Enclose the code that might throw an exception in try block.It must be used within the method and must be followed by either catch or finally block.

Syntax of try with catch block

try
{
...
}
catch(Exception_class_Name reference_variable_name)  // i.e. catch(RuntimeException ex) { }
{
.......
}

catch block:

Catch block is used to handle the Exception.It must be used after the try block.

Problem without exception handling:

class Test{
public static void main(String []args){
int data=50/0;
System.out.println("rest of the code.....");
  }
}

Output: Exception in thread main java.lang.ArithmeticException:/ by zero

As you see in the above example, rest of the code is not executed i.e. rest of the code..... statement is not printed. But if we want to executed the rest of code..... we have to use Exception handling.

Solution by exception handling:

class Test{
public static void main(String []args){
try{
int data=50/0;
}
catch(ArithmeticException ex)
{
System.out.println(ex);
}
System.out.println("rest of the code.....");
 }
}

Output: Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code.....

Note: Now, as you see in the above example, rest of the code is executed i.e. rest of the code..... statement is printed.

Next>> Multiple catch block in Exception Handling