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

Tuesday, June 21, 2016

Re-throwing an Exception Example Java

What is the difference between throws and throw?

Ans: throws clause is used when the programmer does not want to handle the exception and throw it out of a method.throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block.Hence throw and throws are contradictory.

Re-Throwing an Exception

When an exception occurs in a try block it is caught by a catch block.This means that the thrown exception is available to the catch block .eg.

try
{
   thrown exception;
}
catch(Exception e)
{
 thrown exception;   // re-throw the exception out
}

Program:

/**
 *
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */

class A
{
void method()
{
try
{
String str="Hello";
char ch=str.charAt(5);
}
catch (Exception e)
{
System.out.println("Please see the index is within the range");
throw e;
}
}

}

public class ReThrowingExceptionApp
{
/**
* @param args
*/
public static void main(String[] args)
{
A a=new A();
try
{
a.method();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("I caught re-thrwon exception");
}
}


}

Output:

Please see the index is within the range
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at com.collectionpack.A.method(ReThrowingExceptionApp.java:18)
at com.collectionpack.ReThrowingExceptionApp.main(ReThrowingExceptionApp.java:39)
I caught re-thrwon exception


Is it possible to re-throw exceptions?

Ans: Yes,it is,re-throw an exception from a catch block to another class where it can handled.

Monday, June 20, 2016

throws Clause Example Java

throws Clause

Even if the programmer is not handling run-time exceptions,the java compiler will not give any error related to run-time exception.But rule is that programmer should handle checked exceptions.In case the programmer doe not want to handle the checked exception ,he should throw them out using throws clause.if it is not handled,the compiler expects at least to throw it out.

Program:

/**
 *
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * @author Abhinaw.Tripathi
 *
 */

class Sample
{
 private String name;
 public void accept() throws IOException
 {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name:");
name=br.readLine();
 }

 public void display()
 {
System.out.println("Name:"+name);
 }

}

public class ThrowsClauseApp
{
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
         Sample s=new Sample();
         s.accept();
         s.display();
}

}


Result:

The Java compiler expects here to handle the IOException using try-catch block but as i did not want too then i need to throws like this way.


throw Clause:
There is also a throw clause available in Java to throw an exception explicitly and catch it.

Program:

/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
class ThrowClass
{
public static void demo()
{
System.out.println("Inside demo");
throw new NullPointerException("Exception Data");
}
}

public class ThrowClauseApp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
        
ThrowClass.demo();
}

}

Result:

Inside demo
Exception in thread "main" java.lang.NullPointerException: Exception Data
at com.collectionpack.ThrowClass.demo(ThrowClauseApp.java:15)
at com.collectionpack.ThrowClauseApp.main(ThrowClauseApp.java:27)

Note:
  1. throw clause is used in software testing to test whether a program is handling all the exceptions as claimed by the programmer. 
  2. throw clause can be used to throw our own exceptions also.We can also create our own exceptions which are called User-Defined exceptions.We need the throw clause to throw the user-defined exceptions.
Types of Exception 

As you have read out the exceptions,Lets move to understand the types of exception
  • Built-in Exceptions
  • User-defined Exceptions
Built-in Exceptions

  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ClassNotFoundException
  • FileNotFoundException
  • IOException
  • InterruptedException
  • NoSuchFieldException
  • NoSuchMethodException
  • NullPointerException
  • NumberFormateException
  • RuntimeException
  • StringIndexOutOfBoundsException
User-defined Exceptions

User can also create his own exception which are called User-defined Exception.

Should use following steps to create:

  • The user should create an exception class as a subclass to Exception class. Since all exception are sub classes of Exception class,the user should also make his class a subclass to it.
 class MyException extends Exception
  • User can write a default constructor in his own exception class.
  • User can create a parameterized constructor with a string as a parameter.He can use this to store exception details.He can call super class(Exception) constructor from this and send the string there.
MyException(String str)
{
    super(str);
}
  • When the user wants to raise his own exception he should create an object to his exception class and throw it using throw clause as,
MyException me=new MyException("Exception Details");
throw me;

Program:


/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
class MyException extends Exception
{
private static int accno[]={1001,1002,1003,1004,1005};
private static String name[]={"Abhinaw","Sandeep","Anand","Manish","pawan"};
private static double bal[]={10000,25000,58552,785585,8745895};
public MyException() {
// TODO Auto-generated constructor stub
}
public MyException(String str)
{
super(str);
}
}

public class UserDefinedExceptionApp 
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Accoun" + "\t" + "Name" + "\t" + "bal" + "\t");
for(int i=0;i<5;i++)
{
if(bal[i] < 10000)
{
MyException me=new MyException("The amount is less");
try {
throw me;
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

}


Exception Handling Example Java

Exception Handling

When there is an exception ,the user data may be corrupted.This should be tackled by the programmers be carefully designing the program.He/She should watch this 3 steps:

  1. The programmer should observe in his program where there may be a possibility of exception.Such statements should be written inside a try block.                                                               try{statement;}                                                                                                                                                                                                                                                                                  The greatness of try block is that even if some exception arises inside it,the program will not be terminated.
  2. The programmer should write the catch block where he should display the exception details to the user.                                                                                                                                                     catch(ExceptionClass ref){statements;}
  3. Finally,the programmer should perform clean up operations like closing the files and termination of threads.                                                                                                                     finally{statements;} 
Program:


/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class EceptionHandlingApp 
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
System.out.println("open file");
 int n=args.length;
 System.out.println("n= + " +n);
 int a =45/n;
 System.out.println("a "+a);
 System.out.println("Close File");
}
catch (Exception e)
{
e.printStackTrace();
}

}

}

Output: 

open file
n= + 0
java.lang.ArithmeticException: / by zero
at com.collectionpack.EceptionHandlingApp.main(EceptionHandlingApp.java:22)

Handling Multiple Exceptions:

Most of the times there is possibility of more than one exception present in the program.In this case programmer should use more than one catch blocks.

Program:

/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MultipleExceptionHandlingApp {

/**
* @param args
*/
public static void main(String[] args)
{
 try
 {
System.out.println("open file");
 int n=args.length;
 System.out.println("n= + " +n);
 int a =45/n;
 System.out.println("a "+a);
 int b[]={10,20,30};
 b[50]=100;
 
 catch (ArithmeticException e)
 {
e.printStackTrace();
 }
 catch (ArrayIndexOutOfBoundsException e)
 {
 System.out.println("ArrayIndexOutOfBoundsException ");
e.printStackTrace();
 }
 
 finally
 {
 System.out.println("Close File");
 }
 
}

}

Output:

open file
n= + 0
Close File
java.lang.ArithmeticException: / by zero
at com.collectionpack.MultipleExceptionHandlingApp.main(MultipleExceptionHandlingApp.java:22)


This means, even if there is scope for multiple exceptions,only one exception at a time will occur.


Bullet Points in Exception Handling:
  • An exception can be handled using try,catch and finally blocks.
  • It is possible to handle multiple exceptions using multiple catch blocks.
  • Even though there is multiple exceptions,only one exception at a time will occur.
  • We can not write catch without try block.
  • It is not possible to insert some statement within try{} and catch() blocks.
  • Nested try can be possible.

Exception Handling Beginning Java Exapmle

Exception Handling

A software engineer commit many errors while developing software code.These errors are also called Bugs and the process of removing them is called debugging.Let us take a look at different type of bugs.

Errors in a Java Program

There are basically three types of errors in the Java program.


  1. Compile-time Errors
  2. Run-time Errors
  3. Exceptions
  • Compile-time Errors: These are syntactical errors found in the code due to which a program fails to compile.
Program:


/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class CompileTimeErrorApp {

/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Hello")
System.out.println("Here is the error")
}

}

This program will fail to compile because there are no semi-colons at the end of System.out.println("Hello") .

Output: 

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Syntax error, insert ";" to complete BlockStatements
Syntax error, insert ";" to complete Statement

at com.collectionpack.CompileTimeErrorApp.main(CompileTimeErrorApp.java:17)

  • Run-time Errors:
  These errors are produced at run time because it represents the inefficiency of the computer system to execute  a particular statement.

Program:

/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class RuntimeErrorApp {

/**
* @param args
*/
public static void main()
{
System.out.println("Run time Exception is here);

}

}

Output: NoSuchMethod Error:main

What happens if main() method is written without String args[] ?
Ans: The code will compile but JVM can not see the main() method without String args[] .

  • Exceptions:
    Basically, an exception is a  run-time error.Then there arises a doubt: Can not I call compile time error  an exception? The Answer is No. you can not call compile-time errors also exception.They come under errors.All exceptions occur only at run-time but some exception are detected compile time and some others at run-time.

The exception checked at compile time by Java compiler are called Checked Exception.
The exceptions that are checked by the JVM are called Unchecked Exception.

The unchecked exceptions and errors are considered as Unrecoverable and the programmer  can not do anything when they occur.
Such as IOException is an example for checked exception.So we threw it out  without handling it.This is done by throws clause .

All exception are declared as classes . in Java of course ,everything is a class in Java.Even errors are also represented by classes.

All these classes are descended from a super class called Throwable.

What is Throwable?
Ans: Throwable is a class that represents all errors and exceptions which may occur in Java.

Which is the super class for all exceptions and an error?
Ans: Exception is the super class of all exceptions in java.

What is the difference  between an exception and an error?
Ans: An exception is an error which can handled it.It means when an exception happens,the programmer can do something to handle it but an error which can not be handled.

Program: 

/**
 * 
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ExceptionAnErrorApp {

/**
* @param args
*/
public static void main(String[] args) 
{
      System.out.println("open file");
      int n=args.length;
      System.out.println("n= + " +n);
      int a =45/n;
      System.out.println("a "+a);
      System.out.println("Close File");
}

}

Output:

open file
n= + 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.collectionpack.ExceptionAnErrorApp.main(ExceptionAnErrorApp.java:20)