28
Exception-Handling Fundamentals A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception

Exception-Handling Fundamentals A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Embed Size (px)

Citation preview

Page 1: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Exception-Handling Fundamentals

A Java exception is an object that describes an

exceptional (that is, error) condition that has occurred in

a piece of code.

When an exceptional condition arises, an object

representing that exception is created and thrown in the

method that caused the error. That method may choose to

handle the exception itself, or pass it on. Either way, at

some point, the exception is caught and processed.

Page 2: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Contd…..

Exceptions can be generated by the Java run-time system, or

they can be manually generated by your code.

Exceptions thrown by Java relate to fundamental errors that

violate the rules of the Java language or the constraints of the

Java execution environment. Manually generated exceptions

are typically used to report some error condition to the caller

of a method.

Java exception handling is managed via five keywords: try,

catch, throw, throws, and finally.

Page 3: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Exception-Handling Block

try {

// block of code to monitor for errors

}

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

}

catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

}

finally {

// block of code to be executed before try block ends

}

Page 4: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Exception Types

All exception types are subclasses of the built-in class

Throwable. Thus, Throwable is at the top of the exception class

hierarchy.

Immediately below Throwable are two subclasses that partition

exceptions into two distinct branches. One branch is headed by

Exception.

This class is used for exceptional conditions that user

programs should catch. This is also the class that you will

subclass to create your own custom exception types.

Page 5: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

There is an important subclass of Exception, called

RuntimeException.

Exceptions of this type are automatically defined for the

programs that you write and include things such as division by

zero and invalid array indexing.

The other branch is topped by Error, which defines exceptions

that are not expected to be caught under normal circumstances

by your program.

Exceptions of type Error are used by the Java run-time system

to indicate errors having to do with the run-time environment,

itself. Stack overflow is an example of such an error.

Page 6: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Uncaught Exceptions Before you learn how to handle exceptions in your program, it is useful

to see what happens when you don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error.

Class error1

{

public static void main( String args[ ])

{

int a=10;

int b=5;

int c=5;

int x=a/(b-c);

System.out.println(“x” +x);

int y= a/(b+c);

System.out.println(“y” +y);

} }

Page 7: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Using try-catch blockClass error2{

public static void main( String args[ ]){ int a=10;

int b=5;int c=5;int x, y;

try {

x= a/( b-c);}

Page 8: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Catch (AirthmeticException e)

{

System.out.println(“division by Zero”);

}

y=a/(b+c);

System.out.println(“y” +y);

}

}

Page 9: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Why do I have put an f after a floating point constants

• The f suffix directs the compiler to create a float

value a sequence of characters representing a

floating point number (a float literal) – otherwise

the compiler would by default create either a

double value or an int value.

Page 10: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Multiple catch Clauses

• In some cases, more than one exception could be raised by

a single piece of code. To handle this type of situation, you

can specify two or more catch clauses, each catching a

different type of exception. When an exception is thrown,

each catch statement is inspected in order, and the first one

whose type matches that of the exception is executed. After

one catch statement executes, the others are bypassed, and

execution continues after the try/catch block.

Page 11: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Multiple Catch Statementstry

{ statement; // generates an exception

}

catch (Exception_type-1 e)

{ Statement; }

catch (Exception_type-2 e)

{ Statement; }

Catch (Exception_type-3 e)

{ Statement;}

Page 12: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Multiple Catch statementsclass multicatch{ public static void main( String args[ ])int a [ ] = {5, 10};int b=5;try { int x= a[2] /b-a[1]; }catch( ArithmaticException e) { System.out.println(“Division by Zero”); }

Page 13: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

catch( ArrayIndexOutOfBoundsException e) { System.out.println(“array index array”); }

catch( ArrayStoreException e) { System.out.println(“ Wrong Data type”); }

Page 14: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Nested try statement

• The try statement can be nested. That is, a try statement

can be inside the block of another try. Each time a try

statement is entered, the context of that exception is

pushed on the stack. If an inner try statement does not

have a catch handler for a particular exception, the stack is

unwound and the next try statement’s catch handlers are

inspected for a match. This continues until one of the catch

statements succeeds, or until all of the nested try

statements are exhausted. If no catch statement matches,

then the Java run-time system will handle the exception.

Page 15: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Nested try statements

class nestTry

{ public static void main( String args[ ])

try {

int a= args.length;

int b= 42/a;

System.out.println(“ a” +a);

try {

if(a==1)

a=a/(a-a);

Page 16: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Contd……If(a==2)

{ int c[ ]= {1};

c[42]=99;

} }

catch(ArrayIndexOutOfBoundsException e)

{ System.out.println(“ Array index out of bounds” +e) }

Catch((AirthmaticException e) {

System.out.println(“ divided by 0:” +e);

} }

}

Page 17: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

throw statement

So far, We have only been catching exceptions that are thrown by the java run-time system. However, it is possible for your program to throw statement. The syntax is:

throw ThrowableInstance; Throwableinstance must be an object of type throwable or subclass of Throwable.

Page 18: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Example of throw statementClass throwdemo

{

static void demoproc()

{ try {

throw new NullPointerException(“demo”)

}

Catch(NullPointerException e){

System.out.println(“caught inside demoproc”);

Throw e; // rethrow the exception

} }

Page 19: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Contd………..public static void main( String s[ ])

{

try {

demoproc();

}

catch(NullPointerException e)

{

System.out.println(“Recaught” +e);

} }

}

Page 20: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Output

Caught inside demoproc.

Recaught: java.lang.NullPointerException:demo

Page 21: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Finally statement Finally statement is used to handle an

exception that is not caught by any of the catch statements. Finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block.

Page 22: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Syntax of finally statement

try try { ………. { ………. ………. ………. } } finally { catch ( ….) ………. { ……….. } } finally{ ……… }

Page 23: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Use of Interface

1. To incorporate multiple inheritence in Java Application.

2. To Develop Distributed applications.

Page 24: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Difference between java and java script

• Java language can stand on its own and creates "standalone" applications while JavaScript must be placed inside an HTML document to function.

• Java must be compiled into what is known as a "machine language" before it can be run. You can alter JavaScript that are in an HTML document after it runs and run it again and again. If you alter java program you need to compile it again before run.

Page 25: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Creating Your Own Exception Subclasses

• Although Java’s built-in exceptions handle most

common errors, you will probably want to create your

own exception types to handle situations specific to

your applications.

• This is quite easy to do: just define a subclass of

Exception. Your subclasses don’t need to actually

implement anything—it is their existence in the type

system that allows you to use them as exceptions.

Page 26: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Creating and throwing your own exception

import java.lang.Exception;

class myexception extends Exception

{ myexception(String message)

{

super(message);

}

class testmyexcp

{ public static void main(Strings args[ ])

{ int x=5, y=1000;

try {

float z=(float) x/ (float) y;

if( z < 0.01)

{

Page 27: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Contd….throw new myexception(“number is too small”);} }catch (myexception e)

{ System.out.println(“caught my exception”);System.out.println(e.getmessage( ) );

}finally{ system.out.println(“ I m always here”);} } } }

Page 28: Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of

Java’s Built-in Exceptions