30
Chapter 9 Exception Handling ICT Academy of Tamil Nadu ELCOT Complex, 2-7 Developed Plots, Industrial Estate, Perungudi, Chennai 600 096. Website : www.ictact.in , Email : [email protected] , Phone : 044 4290 6800 , Fax : 044 4290 6820

Chapter 9 Exception Handling - refer-electrical.weebly.com · Chapter 9 Exception Handling ... The errors must be checked manually in languages that does not support ... ” The error

  • Upload
    docong

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

Chapter 9

Exception Handling

ICT Academy of Tamil Nadu ELCOT Complex, 2-7 Developed Plots, Industrial Estate, Perungudi, Chennai 600 096.

Website : www.ictact.in , Email : [email protected] ,

Phone : 044 4290 6800 , Fax : 044 4290 6820

Table of Contents

1. EXCEPTION HANDLING ..................................................................................... 4

1.1. Exceptions Overview ................................................................................ 4

1.2. Catching Exceptions ................................................................................. 7

1.3. The finally Block ...................................................................................... 10

1.4. Exception Methods .................................................................................. 13

1.6. Defining and Throwing Exceptions ........................................................... 22

1.7. Errors and Runtime Exceptions ................................................................ 24

1.8. Assertions ................................................................................................ 26

EXCEPTION HANDLING

Page 1

9

Chapter 9

Exception Handling

EXCEPTION HANDLING

9 Documentation Conventions

The following conventions are used in this guide:

When you see this… This is…

Recall learning

Case study

Did you know?

Class session

Activity

Quiz

Reference

Indented text in different

font Code snippet

Documentation Conventions

The following conventions are used in this guide:

This is…

Recall learning

Case study

Did you know?

Class session

Activity

Reference

Code snippet

Page 2

EXCEPTION HANDLING

Page 3

9 Chapter 9: Exception Handling

This chapter is about exception handling mechanism. An exception is an abnormal condition

that arises in a code sequence at run time or simply put, an exception is a run-time error.

The errors must be checked manually in languages that does not support exception

handling.

Java’s exception handling avoids these problems and this process, brings run-time

error management into the object-oriented world. We will learn about exception handling

in detail in the following chapter.

EXCEPTION HANDLING

Page 4

9 1. Exception Handling

Exception is, an instance or case not conforming to the general rule.. Exception handling is

the process of handling the errors and nonconforming states, while the program is

executed.

1.1. Exceptions Overview

The following are the Exception or Errors that occurs while running a program.

1. Syntax Errors

2. Logical Error

3. Exception or runtime error.

Syntax Error:

It occurs when the programmer breaks the language rules. During compilation time this

syntax error will be shown. For example the main method should be written as public static

void main(String args[]) but if a programmer writes “public static VOID main(STRING

args[])” The error will be displayed during compilation.

Logical error:

Consider a programmer writing a program with an argument, the argument type is integer

but the programmer has given parameter value as string data type. Here the data type is

mismatched, the argument is integer but the passing parameter is string value, hence error

occurred, it is called as logical error.

Eg:

public static void main(String args[])

{

Example ob=new example();

Ob.meth(“error”); // passing parameter is string

object. Here error occurred.

}

EXCEPTION HANDLING

Page 5

9 Exception

It occurs during the run time hence it is called run time error. If an error occurs in runtime, ,

the programmer can identify the error using print statement. It can print error message or

syntax message.

The exceptions are synchronous and asynchronous.

The Nature of Exceptions

1. Programming Error: Exception generated by the programming error.

Eg: NullPointerException

2. Client Code Error: Sometimes, API doesn’t allow something from the client code.

The client take some alternative action to give the information provided in the

exception.

3. Checked Exception: Normally, all exception programs extends/inherit the Exception

class for checking exceptions. The API throws checked exceptions, both in a catch or

throw class.

4. Unchecked exceptions: All the exceptions extend from RunTimeException, but this

RunTimeException extends from Exception Class. There is no conditional client side

code to deal with them, they are called unchecked exception

Synchronous Exception

1. Exceeding the maximum limit of an array.

2. Out of memory.

3. Division by zero.

4. Disc is not enough memory.

Asynchronous Exception:

1. Disk error

2. Keyboard problem.

All synchronous error occurs within the program control. But asynchronous exception

occurs beyond the program.

Handling the Exception:

EXCEPTION HANDLING

Page 6

9 Exception is nothing but run time error occurring during the programs run time. Exception

handling is a mechanism to deal with the exceptions. Java is done with the help of

exception objects.

Advantage of Exception Handling.

1. It avoids uncharacteristic situation during run time.

2. It gives the error report

Types of Exception

• Arithmetic Exception

Whether arithmetic error occurs it finds and gives the error report.

• IOException

Find the Input output failure while not able to read the file.

• ArrayIndexBounds Exception

Finds the array index error which exceeds the index limits.

• ClassNotFound Exception

Finds whether the class is defined or not in a file.

The above classes are exception classes for handling various types of errors. All classes

derived from throwable class. ‘Throwable’ is the super class of the exception class.

Hierarchy of Exception classes

Super Class

Sub-Classes

Throwable Class

Error Exception

ClassNotFound Exception Runtime Exception IOException

Internal Error Arithmetic Exception IndexOutOfBound Exception

Virtual Machine Error

EXCEPTION HANDLING

Page 7

9

1.2. Catching Exceptions

Catching an exception means, this method is used to catch the thrown exception objects

from try block by the corresponding catch block.

Try and catch:

Try is a block; the program generates the error in the try block.

Catch is a block; catch the errors from the try block.

Structure of try and catch block:

Class exception1

{

Declare or define the Variables;

Try

{

Statements for checking the errors

}

Catch(ExceptionClass object)

{

Statements for catch and handling the error.}

Try and catch is the keyword.

Error occurs within the statements in the try and catch block, it throws error automatically.

The thrown exception is fixed by the corresponding catch block. Then it executes the

statements for handling the exception.

Try block:

This block is particularly used to test the program statements when the run time errors

occur. If error is found, the try block throws the error and it is catched by catch block. In

single program we can have more than one try block.

The exception is thrown by try block automatically when error occurs with the help of

statement throw. If we know while writing a program that is may cause error in the

program, we can throw the exception explicitly. It is called throwing an exception.

EXCEPTION HANDLING

Page 8

9

Syntax:

try

{

Statements;

Throw exceptions object }

Example Program

import java.io.*;

public class exception1

{

public static void main(String[] args) throws

Exception{

try

{

int numeric;

BufferedReader in = new BufferedReader(new

InputStreamReader(System.in));

System.out.print("Enter Your Name:");

numeric = Integer.parseInt(in.readLine());

}

catch(NumberFormatException ex) // catch block

with an argument

{

System.out.println("You are entered"+"

"+ex.getMessage()+" " + "Catch the Exception:No numeric

value.");

System.exit(0);

} }}

EXCEPTION HANDLING

Page 9

9

Output

Catch clause using throw statement.

Syntax: throw new name of Exception(arguments);

import java.io.*;

public class exceptioncatch

{

public static void main(String args[])

{

int i=0, j=0;

float x;

BufferedReader b = new BufferedReader(new

InputStreamReader(System.in));

try // start try block

{

System.out.println(" Enter the I value:");

i = Integer.parseInt(b.readLine());

System.out.println(" Enter the J value:");

j=Integer.parseInt(b.readLine());

if(i==0)throw new ArithmeticException(); // trow

statment

x=i/j;

System.out.println(" X value is:"+x);

}

EXCEPTION HANDLING

Page 10

9 catch(IOException ie) // catch block with the argument

of IOException

{

System.out.println(ie);

}

catch(ArithmeticException ae) // catch block with the

argument of ArithmeticException

{

System.out.println("divided by zero");

}}}

Output

1.3. The finally Block

Final is a block like try and catch. Catch block is executed when error occurs in the program,

but finally block executes both error occurred or not occurred.

EXCEPTION HANDLING

Page 11

9 Syntax:

try {

// Block of code with multiple exit points

}

Catch(Exception e)

{

//catch the exception

}

finally

{

// Block of code that is always executed when the

try block is exited,

// no matter how the try block is exited

}

Java is used finally in a block along with the try block and catch block, but it is optional in

exception handling. The final block is mainly used to perform cleaning behavior following

the the code in the try block. When an exception occurs in try block , it throws an exception

to catch the block , the remaining try block code does not get executed at that time. We

may need to clean up the objects used in try block. This block contains statements which are

used to free the resources used in try and catch blocks and also other valid statements.

Example Program

EXCEPTION HANDLING

Page 12

9 import java.io.*;

public class finallyexample

{

public static void main(String args[])

{

int a=0,b=0,c=0;

BufferedReader b1 = new BufferedReader(new

InputStreamReader(System.in));

try

{

System.out.println(" Enter a value");

a = Integer.parseInt(b1.readLine());

System.out.println(" Enter b value");

b = Integer.parseInt(b1.readLine());

if(a==0)// throws new ArithmeticException();

c=a/b;

System.out.println(" Ratio"+c);

}

catch(IOException e)

{

System.out.println(e);

}

finally

{

System.out.println("Finally block executed end the

cxecution");

}}

}

Output:

EXCEPTION HANDLING

Page 13

9

1.4. Exception Methods

Java creates an object of exception methods whether error occurs in the program or not.

The exception Object is indicates the type of errors and status of program while the error

occurred.

Following methods is to be used for handling exceptions; it is also called as keyword.

• Try

• Catch

• Throw

• Throws

• Finally

Try block:

It contains set statements, it creates an exception within the method. If the exception is

raised in the try block, it throws the exception to the catch block, and this happens

automatically. Each try block has one catch block. ‘

Working of try and catch blocks with an example

EXCEPTION HANDLING

Page 14

9 class notryblock

{

public static void main(String args[])

{

int a=0;

int b=2;

int c=b/a;

System.out.println("The c value is = " +c);

}

}

Output with an error/Exception

How to rectify this exception using try-catch methods:

Handling the exception by implementing try and catch block in this program. If an exception

arises in a try block the exception handler will be used to handle the exception.

EXCEPTION HANDLING

Page 15

9 class usingtryblock {

public static void main(String args[])

{

int a = 0,b=2,c=0;

try

{

c=b/a;

System.out.println("The result is=" +c);

}

catch(ArithmeticException e)

{

System.out.println("Divide by Zero");

}}}

Output

Using throw

The throw statement is used to throw an exception. For example, if you have entered values

in a program it needs to thrown an exception. The throw normally terminate the execution

during normal flow of java code. Using Throw statement the controls are handled to catch

block. If there is no catch block, then program terminates.

The Syntax used to declare the throw statement:

EXCEPTION HANDLING

Page 16

9 throw obj // obj is object of the Throwable class

The obj is an object of the class Throwable. Object created using new operator. The

compiler gives you an error if the obj does not belong to a valid class of Exception.

Example Program

class usingthrow {

static void meth() {

try

{

throw new IllegalStateException();

}

catch (NullPointerException se)

{

System.out.println("No exception catch");

}

}

public static void main(String args[])

{

try

{

meth();

}

catch(IllegalStateException se1)

{

System.out.println("Catch exception is:"+ se1);

}}}

Output

EXCEPTION HANDLING

Page 17

9

Throws

Throws throw the exception during runtime. Throws is a keyword, it is basically reserved

words which have specific meaning relevant to a compiler. The throws keyword in java

programming language is applicable to a method that raises particular type of exception

while being processed.

The throws keyword takes arguments as a list of the objects of type Throwables class.

When we use the throws with a method it is known as ducking. The method calling a

method with a throws clause is needed to be enclosed within the try catch blocks.

Difference between throw and throws keywords

An exception throws is used to catch or finally block, we use throw keyword. It can also pass

routine information to your exception handling module.

throw new MyException ("Information");

Throws keyword is used to a particular exception thrown to the catch block. Throws

surrounding method instead of try and catch exception handler.

static int c(int a, int b) throws MyException

EXCEPTION HANDLING

Page 18

9 import java.io.IOException;

public class Class1{

public method readingFile(String file) throws

IOException{

<statements>

if (error){

throw new IOException("error reading file");

}

}

}

Finally

Finally block is executed to check whether an error is thrown or not, before executing the

exception handler. After executing statements in the finally block, the control is transferred

to the first statement after the finally block.

EXCEPTION HANDLING

Page 19

9 Example program:

import java.io.*;

public class usingfinally

{

public static void main(String args[])

{

int a=0,b=5,c=0;

try

{

c=b/a;

System.out.println(" Ratio"+c);

}

catch(ArithmeticException ae)

{

System.out.println(" Diveded by zero");

}

finally

{

System.out.println("Finally block executed end the

cxecution");

}

}

}

9.5. Declaring Exceptions

Throws() declaration:

A method that throws an exception in method, using the throws declaration:

EXCEPTION HANDLING

Page 20

9 public void meth() throws EmptyStackException

This is mandatory for all exceptions except for Runtime Exceptions and its subclasses

Exceptions that have to be advertised are called checked exceptions. When a method gives

an exception class, it may actually throw exception of this class Or its subclasses.

public meth() throws IOException

{

throws new IOException ();

throws new EOFException();

}

Advantage:

Subclasses will override this method.

Disadvantage:

This method will maybe catch the exception that was showed

catch (IOException e). It will lose the details possible from subclass, unless it knows to cast.

Catch or Declare Requirement

Java requires that methods either catch or declare all non-runtime exceptions that can be

thrown within the method. Method has "catch", "declare", "non-runtime exceptions", and

"the exceptions that can be thrown within the scope of the method".

Catch

An exception handler catches exception in the method for the related exceptions.

Declare

The method must declare a throw if it does not catch the exception.

An interface is one part of method; it can be used to throw the exception. Method must

know about the exception that method can throw in order to consciously decide how to

handle the exceptions. Declare the exceptions that can be thrown within the scope

methods in the method signature.

EXCEPTION HANDLING

Page 21

9 Non-runtime Exceptions

There are different type exceptions like IOException, Arithmetic Exception and runtime

exceptions. Run time exceptions are occurring within the java runtime environment. It

includes arithmetic exceptions, pointer exception and indexing exceptions.

Runtime exceptions can occur anywhere in a program. Frequently checking for runtime

exceptions remuneration of catching them. Thus the compiler does not require that you

catch or declare runtime exceptions. Declare all exceptions as runtime exceptions.

Runtime Exceptions--The disagreement contains a thorough conversation about when and

how to use runtime exceptions.

Declaring the Exceptions Thrown by a Method

The writeList() method doesn't catch the exceptions that occurs within it, then the

writeList() method must declare that it can throw them. Let's modify the writeList() method

to declare the methods that it can throw. To remind you, here's the writeList() method

again.

public void writeList() {

System.err.println("Entering try statement");

int i;

pStr = new PrintStream(

new BufferedOutputStream(

new FileOutputStream("OutFile.txt")));

for (i = 0; i < size; i++)

pStr.println("Value at: " + i + " = " +

victor.elementAt(i));

}

Array Index Out Of Bounds Exception is a subclass of RuntimeException

The writeList() throws these two exceptions,

EXCEPTION HANDLING

Page 22

9 o a throws clause to the method signature for the WriteList() method.

o The throws clause is composed of the throws keyword list of all the

exceptions thrown by that method.

Syntax:

public void writeList() throws IOException,

ArrayIndexOutOfBoundsException {}

1.6. Defining and Throwing Exceptions

Exception:

Exception is nothing but an error, It occurs during the run time, hence called as called run

time error. During the run time if an error occurs, the programmer can identify the error

using print statement. It can print our own error message or syntax message. Java virtual

machine indicates this error to the program as an exception. Every exception is represented

by a reference of the class Throwable or one of its subclasses. The class object can be used

to bear the information from the point at which an exception occurs to the handler that

catches it.

Throwing Exceptions using throw statement.

Throw- throws the exception when an error occurs in a program,

Eg: user id or password entered invalid.

Using the throw Statement

1. The throw statement causes termination of the normal flow of control of the java

code and stops the execution of the subsequent statements.

2. The throw clause transfers 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

EXCEPTION HANDLING

Page 23

9 Syntax to declare the throw statement,

throw ThrowableObj

Example Program without using throw statement.

import java.io.*;

class throwexample

{

public static void main(String args[])

{

try

{

throw new IllegalStateException ( );

}

catch (NullPointerException np)

{

System.out.println ("Not Caught by the catch block inside

meth().");

}}}

Output:

EXCEPTION HANDLING

Page 24

9 Example program with throw statement

class throwexample1

{

static void meth( ) throws ClassNotFoundException

{

System.out.println ("Using throw statement");

throw new ClassNotFoundException ( );

}

public static void main (String args [ ])

{

try

{

meth( );

}

catch ( ClassNotFoundException obj)

{

System.out.println ("Method using throw statement

throwing exception. :" +obj);

}}}

Output

1.7. Errors and Runtime Exceptions

Error occurs when the programmer breaks the language rules. During compilation time this

syntax error will be shown. For example a printing statement System.out.print(“Error”); the

EXCEPTION HANDLING

Page 25

9 first letter of system starts with capital letter S, but programmer writes

System.out.println(“error”); while compile time compiler show the syntax error.

Logical error:

When a programmer writes a program instead of integer is the parameter passed by him is a

string then error occurs. As data type is mismatched logical error occurs here.

Runtime Exception:

Java handles two types of exceptions 1. Runtime exceptions and 2. Checked exception. The

checked exception extends from Exception class and the runtime exception form the

RunTime Exception class. Method that throws exception to catch block or throw the

exception itself, this exception extends from exception class.

Methods that throws a runtime exception is not required to catch the runtime exception,

method name not required to declare as runtime exception.

Checked exceptions indicate an exceptional condition from which a caller can conceivably

recover. Runtime exceptions indicate a programmatic error from which a caller cannot

normally recover. Checked exceptions force to catch the exception. Always catch block

checked exception once reach a point. Code can make a meaningful attempt at recovery. It

is best to catch runtime exceptions.

Example Program

public class runtime1

{

static void meth()

{

throw new RuntimeException("Runtime Exception from

meth()");

}

static void meth1() {

meth();

EXCEPTION HANDLING

Page 26

9 }

public static void main(String[] args) {

meth1();

}}

1.8. Assertions

Assert is a statement, it is a part of java assertion. This statement is used to code testing and

debugging.

Format: assert boolean_expression : string_expression;

Boolean_expression is true, the statement will pass normally. If boolean_expression is false,

the statement will fail with an "Assertion" exception.

Example program

public class usingassert

{

private int days = 0;

public static void main(String[] arg)

{

int i = Integer.parseInt(arg[0]);

usingassert o = new usingassert(i);

System.out.print("Name of the in a week:

"+o.getDayOfWeek());

}

public usingassert(int a) {

days = a;

}

public String getDayOfWeek() { if (days % 7 == 0) {

return "Sunday";

EXCEPTION HANDLING

Page 27

9 } else if (days % 7 == 1) {

return "Monday";

} else if (days % 7 == 2) {

return "Tuesday";

} else if (days % 7 == 3) {

return "Wednesday";

} else if (days % 7 == 4) {

return "Thursday";

} else if (days % 7 == 5) {

return "Friday";

} else {

assert days % 7 == 6 : days;

return "Saturday";

} }}

Output

EXCEPTION HANDLING

Page 28

9 Exercise

1. Write a program to show how to throw an exception

2. Write a program illustrating try, catch & finally methods.

3. Explain about how to handle exceptions

4. Write a program to create your own exception subclass that throws exception if the sum

of the two integers is greater than 100

5. Write a program to catch more than three exceptions

Summary

From the above chapter we are familiar with

� Exception handling

� Catching exceptions

� Finally block

� How to declare exceptions

� How to define and throw exceptions