Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

EXCEPTION HANDLING

EXCEPTION HANDLING

Unit Structure

7.0 Objective
7.1 Introduction
7.2 Overview
7.3 What is Exceptions and handling exception?
7.3.1 Compile time errors
7.3.2 Run time errors
7.3.3 try…catch:
7.3.4 Using Multiple catch Blocks
7.3.5 finally Block
7.3.6 Throwing an Exception
7.3.6.1 Using the throw Statement
7.3.6.2 Using the throws Statement
7.3.9 Creating and Using Your Own Exception Classes
7.4 Summary:
7.5 List of references
7.6 Bibilography

7.0 Objective: In this lesson of Java Tutorial, you will learn...

1. The exception handling mechanism.
2. Write try ... catch structures to catch expected exceptions
3. Use finally blocks to guarantee execution of code
4. Throw/ Throws exceptions

7.1 Introduction

An exception is an event, which occurs during the execution of the program, that an interrupt the normal flow of the program‘s instruction. In other words, Exceptions are generated when a recognized condition, usually an error condition, arises during the execution of a method. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions. For each method that could throw an exception, your code must report to the Java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception. Exception handling is basically use five keyword as follows:


  • try 
  • catch 
  • throw
  • throws 
  • finally

7.2 Overview

Exceptions are generated when an error condition occur during the execution of a method. It is possible that a statement might throw more than one kind of exception. Exception can be generated by Java-runtime system or they can be manually generated by code. Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as
 Run out of memory
 Resource allocation Error
 Inability to find a file
 Problems in Network connectivity.

In this unit we will learn the exception handling mechanism.

7.3 What is Exceptions and handling exception?

Exceptions are generated when a recognized an error condition during the execution of a program. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions


  • for each method that could throw an exception, your code must report to the Java compiler that it could throw that exact exception.
  • the compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception.

There are two ways to handle an exception:



  • you can try the "risky" code, catch the exception, and do something about it, after which the transmission of the exception come to an end 
  • you can mark that this method throws that exception, in which case the Java runtime engine will throw the exception back to the method.

So, if you use a method in your code that is marked as throwing a particular exception, the compiler will not allow that code unless you handle the exception. If the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them equivalent the exception type. The first one that matches will be executed. If none match, then this methods ends, and execution jumps to the method that called this one, at the point the call was made.

Following figure shows the Exception type.


Figure 7.1. A partial view of the Throwable family
An error means fault and there are two types of error as follows:

7.3.1 Compile time errors

Compiler time error means Java compiler identify the syntax error at the time of compilation. And without successfully compilation, compiler does not create .class file. That means we have to compile the program which should be error free and then compiler creates .class file of the program and then we can run the program.

The common problems are:

 Missing braces
 Missing semicolon
 Missing double quote in string
 = instead of == operator
 And so on.

For example:

class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b
System.out.println("Division is+c);
}
}
Output:
C:\cc>javac Try1.java
Try1.java:8: ';' expected
System.out.println("Division is+c);
^
Try1.java:8: unclosed string literal
System.out.println("Division is+c);
^
2 errors

7.3.2 Run time errors

Several time program may compile successfully and compiler creates the .class file of the program but when the time of running the program, it shows the error and that type of error called run time error.
The common problems are:

 Divide by zero

 Conversion of invalid string to number
 access the element that is out of bound of an array
 Passing the parameters with invalid range.
 And so on.
For example: write a program to find out division of two numbers.
class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b;
System.out.println("Division is"+c);
}
}
Output:
C:\cc>javac Try1.java
C:\cc>java Try1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Try1.main(Try1.java:7)

7.3.3 try…catch:

If a method is going to resolve potential exception internally, the line of code that could generate the exception is placed inside a try block


  • There may be other code inside the try block, before and/or after the risky line(s) - any code that depends upon the risky code's success should be in the try block, since it will automatically be skipped if the exception occurs

Syntax –

try
{
code
risky/unsafe code
code that depends on the risky code succeeding
}
There is usually at least one catch block immediately after the try block


  • A catch block must specify what type of exception it will catch

Syntax –

catch (ExceptionClassName exceptionObjectName)
{
code using methods from exceptionObjectName
}


  • There can be more than one catch block, each one marked for a correct exception class 
  • The exception class that is caught can be any class in the exception hierarchy, either a general (base) class, or a very correct (derived) class
  • The catch block(s) must handle all checked exceptions that the try block is known to throw unless you want to throw that exception back to the method. 
  • It is possible to have a try block without any catch blocks if you have a finally block but any checked exceptions still need to be caught, or the method needs to declare that it throws them

If an exception occurs within a try block, execution jumps to the first catch block whose exception class matches the exception that occurred. Any steps remaining in the try block are skipped. If no exception occurs, then the catch blocks are skipped


If declare a variable within a try block, it will not exist outside the try block, since the curly braces define the scope of the variable. You will often need that variable later, if nowhere else other than the catch or finally blocks, so you would need to declare the variable before the try.


If you declare but don't initialize a variable before a try block, and the only place you set a value for that variable is in the try block, then it is possible when execution leaves the try ... catch structure that the variable never received a value. So, you would get a "possibly uninitialized value" error message from the compiler, since it actually keeps track of that sort of thing. Usually this happens with object references; you would also generally initialize them to null.


public class demo

{
public static void main(String[] args)
{
int ans1, ans2;
int a = 2, b = 2, c = 0;
try
{
ans1 = a/b;
System.out.println("a/b = " + ans1);
ans2 = a/c;
System.out.println("a/c = " + ans2);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception!");
}
System.out.println("demo is over");
}
}
Output:
C:\>set path=C:\Java\jdk1.5.0_01\bin
C:\>javac demo.java
C:\>java demo
a/b = 1
Arithmetic Exception!
demo is over
Code Explanation –
The program will print the first result, and then not succeed while performing the division for the second equation. Execution will step to the catch block to print our message on the screen
Example -
The prior example used a RuntimeException, which your code is not obligated to handle. Most methods in the I/O classes throw IOException, which is an exception that you must handle.
Following program shows the use of IOException.
import java.io.IOException;
public class demo
{
public static void main(String[] args)
{
int num = 0;
num = System.in.read();
try
{
num = System.in.read();
System.out.println("You entered " + (char) num);
}
catch (IOException e)
{
System.out.println("IO Exception occurred");
}
}
}
Output:
C:\>javac demo.java
demo.java:11: unreported exception java.io.IOException; must be caught or declar
ed to be thrown
num = System.in.read(); // comment out this line
^
1 error
Code Explanation:
The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The second read attempt is within a try block, as it should be. there is no way we can force an IOException from the keyboard to test the catch block.

7.3.4 Using Multiple catch Blocks

It is possible that a statement might throw more than one kind of exception you can list a sequence of catch blocks, one for each possible exception remember that there is an object hierarchy for exceptions –
class demo
{
public static void main (String args [])
{
int A[] = new int[5];
try
{
for (int c = 0; c <5; c++)
{
//do nothing
}
for (int c = 0; c <5; c++)
{
A[c] = c/ c;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Array out of bound ");
}
catch (ArithmeticException e)
{
System.out.println ("Zero divide error");
}
}
}
Output:
C:\>javac demo.java
C:\>java demo
Zero divide error
C:\>

7.3.5 finally Block

To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try and catch blocks
The code in the finally block will almost always execute, even if an unhandled exception occurs; in fact, even if a return statement is encountered if an exception causes a catch block to execute, the finally block will be executed after the catch block if an uncaught exception occurs, the finally block executes, and then execution exits this method and the exception is thrown to the method that called this method
Syntax –
try
{
risky code/ unsafe code block
}
catch (ExceptionClassName exceptionObjectName)
{
code to resolve problem
}
finally
{
code that will always execute
}
In summary:


  • A try block is followed by zero or more catch blocks 
  • There may one finally block as the last block in the structure. 
  • There must be at least one block from the collective set of catch and finally after the try.

It's possible to have a try block followed by a finally block, with no catch block



  • This is used to prevent an unchecked exception from exiting the method before cleanup code can be executed

Example:

public class demo
{
public static void main(String args[])
{
try
{
System.out.println("Try Block before the error.");
System.out.println(1/0);
System.out.println("Try Block after the error.");
}
catch(java.lang.ArithmeticException e)
{
System.out.println("Catch Block");
System.out.println("A Stack Trace of the Error:");
e.printStackTrace();
//e.getMessage();
System.out.println("The operation is not possible.");
}
finally
{
System.out.println("Finally Block");
}
System.out.println("demo is over");
}
}
Output:
C:\>javac demo.java
C:\>java demo
Try Block before the error.
Catch Block
A Stack Trace of the Error:
java.lang.ArithmeticException: / by zero
at demo.main(demo.java:8)
The operation is not possible.
Finally Block
demo is over

7.3.6 Throwing an Exception

You can throw an exception explicitly using the throw statement.
Example:
You need to throw an exception when a user enters a wrong student ID or password.
The throws clause is used to list the types of exception that can be thrown in the execution of a method in a program.

7.3.6.1 Using the throw Statement

1. The throw statement causes termination of the normal flow of control of the java code and prevents the execution of the subsequent statements.
2. The throw clause convey the control to the nearest catch block handling the type of exception object throws.
3. If no such catch block exists, the program terminates.
The throw statement accepts a single argument, which is an object of the Exception class.
Syntax –
throw ThrowableObj
You can use the following code to throw the IllegalStateException exception:
class demo
{
static void tdemo()
{
try
{
throw new IllegalStateException ();
}
catch (NullPointerException e)
{
System.out.println ("Not Caught by the catch block inside tdemo ().");
}
}
public static void main (String args[ ])
{
try
{
tdemo();
}
catch(IllegalStateException e)
{
System.out.println("Exception Caught in:"+e);
}
}
}
Output
C:\>javac demo.java
C:\>java demo
Exception Caught in:java.lang.IllegalStateException
C:\>

7.3.6.2 Using the throws Statement

The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method.
This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw.
Syntax –
[< access specifier >] [< modifier >] < return type > < method name > [< arg list >] [ throws <exception list >]
Example:.
You can use the following code to use the throws statement:
class demo
{
static void throwMethod ( ) throws ClassNotFoundException
{
System.out.println ("In throwMethod ");
throw new ClassNotFoundException ( );
}
public static void main (String args [ ])
{
try
{
throwMethod ( );
}
catch ( ClassNotFoundException e)
{
System.out.println (" throwMethod has thrown an Exception :" +e);
}
}
}
Output
C:\>javac demo.java
C:\>java demo
In throwMethod
throwMethod has thrown an Exception :java.lang.ClassNotFoundException

7.3.9 Creating and Using Your Own Exception Classes

You can create your own exception class by extending an existing exception class
Syntax –
[modifiers] NewExceptionClassName extends ExceptionClassName
{
create constructors that usually delegate to super-constructors
}
You could then add any fields or methods that you wish, although often that is not required. You must, however, override any constructors you wish to use: Exception(), Exception(String message), Exception(String message, Throwable cause), Exception(Throwable cause). Usually you can just call the equivalent super-constructor. If you extend RuntimeException or one of its subclasses, your exception will be treated as a runtime exception.
When a situation arises for which you would like to throw the exception, use the throw keyword with a new object from your exception class, for example:
Syntax –
throw new ExceptionClassName(messageString);

7.4 Summary:

In this lesson of the Java tutorial you have learned:


  • how Java's exception handling mechanism works 
  • how to try and catch exceptions about the various types of checked and unchecked exceptions 
  • how to write exception classes 
  • how to throw exceptions


No comments:

Post a Comment