Exception Handling Exception Handling Exception Handling

AboMohammad10 33 views 30 slides Apr 28, 2024
Slide 1
Slide 1 of 30
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30

About This Presentation

Exception_Handling


Slide Content

Exception Handling
•WhatisException
•Exception and Error
Throwable
Exception
Error

EXCEPTION HANDLING
•Itiscommontomakemistakeswhiledevelopingaswellas
typingaprogram.
•Amistakemightleadtoanerrorcausingtheprogramto
produceunexpectedresults.
•Errorsarethewrongthatcanmakeaprogramgowrong.
•Anerrormayproduceanincorrectoutputormayterminate
theexecutionoftheprogramabruptlyorevenmaycause
thesystemtocrash.
•Itisthereforeimportanttodetectandmanageproperlyall
thepossibleerrorconditionsintheprogramsothatthe
programwillnotterminateorcrashduringexecution.
•Therearetwotypesoferrors:
Compile-timeerrors
Run-timeerrors

Compile-time errors:
•Thecompile-timeerrorsaredetectedand
displayedbytheJavacompiler,duringthe
compilationoftheprogram.
•Ifaprogramcontainscompile-timeerrors,
thecompilerdoesnotcreatethe.classfile.
•So,itisnecessarytofixalltheerrors.
•Afterfixingtheerrors,theprogramhastobe
recompiled.

Run-time errors:
•Sometimes,aprogrammaycompilesuccessfully
creatingthe.classfilebutmaynotrunproperly.
•Suchprogramsmayproducewrongresultsdueto
wronglogicormayterminateduetoerrorssuch
asstackoverflow.
•Sucherrorsarecalledastherun-timeerrors.
•Exceptionisanabnormalconditionthatarisesin
acodesequenceatruntime.
•Inotherwords,anexceptionisarun-timeerror.

Some of the common exceptions are:
•Dividinganintegerbyzero.
•Accessinganelementthatisoutoftheboundsofanarray.
•Tryingtostoreavalueintoanarrayofanincompatibleclassortype
•Tryingtocastaninstanceofaclasstooneofitssubclasses.
•Passingaparameterthatisnotinavalidrangeorvaluefora
method.
•Attemptingtouseanegativesizeforanarray.
•Accessingacharacterthatisoutofboundsofastring.
•Convertinginvalidstringtoanumber.

Example:
// This program illustrates the run-time errors
classError_Runtime
{
publicstatic voidmain(String args[ ])
{
inti = 10 ;
intj = 2 ;
int k = i/(j-j); // Division by zero
System.out.println("\n k = " + k);
intl = i/(j+j);
System.out.println("\n l = " + l);
}
}
Theaboveprogramissyntacticallycorrectandthereforedoesnot
produceanyerrorduringcompilation.
However,whentheprogramisrun,itdisplaysthefollowingmessage
andstopswithoutexecutingfurtherstatements.
Division by zero

Exceptions
•Anexceptionisarun-timeerror.
•WhentheJavainterpreterencountersanerrorsuchasdividing
anintegerbyzero,itcreatesanexceptionobjectandthrowsit
(informsthatanerrorhasoccurred).
•Iftheexceptionobjectisnotcaughtandhandledproperly,the
interpreterwilldisplayanerrormessageandwillterminatethe
program.
•Ifonewantstheprogramtocontinuewiththeexecutionofthe
remainingcode,thenoneshouldtrytocatchtheexceptionobject
thrownbytheerrorconditionandthendisplayanappropriate
messagefortakingcorrectiveaction.Thetaskisknownas
exceptionhandling.
•Thepurposeofexceptionhandlingmechanismistoprovidea
meanstodetectandreportanexceptionalcircumstancesothat
appropriateactioncanbetaken.
•Javaexceptionhandlingismanagedviafivekeywords:try,
catch,throw,throwsandfinally.
•Theerrorhandlingcodebasicallyconsistsoftwosegments;one
todetecterrorsandtothrowexceptionsandtheothertocatch
exceptionsandtotakeappropriateactions.

JavaExceptions:Someofthecommonexceptionsarelisted
inthefollowingtable:
Exception Meaning
ArithmeticException Arithmetic error, such as divide by zero.
ArrayIndexOutOfBoundsException Array index is out of bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
FileNotFoundException Attempt to access a nonexistent file.
IOException Caused by general I/O failures, such as
inability to read from a file.
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings
and number fails.
OutOfMemoryException Caused when there is not enough memory
to allocate a new object
StringIndexOutOfBoundsException Caused when a program attempts to
access a nonexistent character position in a
string.
SerurityException Caused when an applet tries to perform an
action not allowed by the browser’s security
setting.
StackOverflowException Caused when the system runs out of the
stack space.

SyntaxofExceptionHandlingCode:Thebasicconceptof
exceptionhandlingisthrowinganexceptionandcatchingit.
tryblock
Statement that causes an
exception
catchblock
Statement that handles the
exception
Throws exception
object Exception object creator
Exception handling mechanism

Cont.
•Java uses a keyword try to preface a block of code that is likely to cause an
error condition and throw an exception.
•A catch block defined by the keyword catchcatches the exception thrown by the
tryblock and handles it appropriately.
•The catch block is added immediately after the tryblock.
•The general form of exception handling block is:
try
{
// Block of code to monitor for errors
}
catch(Exception-type1 exOb)
{ // Exception handler for Exception Type1 }
catch(Exception-type2 exOb)
{ // Exception handler for Exception Type2 }
…………….
…………….
finally
{ // Block of code to be executed before try block ends}
•Here, Exception-typeis the type of exception that has occurred.

Nowconsiderthefollowingprogram,thatillustratestheuse
ofthetryandcatchtohandleexception.
// This program illustrates the use of the try and catch for exception handling
class TryCatch
{
public staticvoid main(String args[ ])
{
int i = 10 ;
intj = 2 ;
int k, l ;
try
{
k = i / ( j –j ); // Exception
}
catch(ArithmeticException e) // Exception will be caught here
{
System.out.println("\n Division by zero");
}
l = i/(j+j);
System.out.println (" l = " + l);
}
}

Cont.
•Theaboveprogramdisplaysthefollowingoutput:
•Divisionbyzero
•l=2
•Notethattheaboveprogramdidn’tstopatthepointof
exceptionalcondition.
•Itcatchestheerrorcondition,printstheerrormessage,
andthencontinuestheexecution,asifnothinghas
happened.
•Noticethatthepreviousprogramdidnotdisplaythe
valueofl.

Now,considerananotherprogramofexceptionhandlinginwhichthetry….catch
blockcatchestheinvalidentriesinthelistofthecommandlinearguments.
classNumber_Format_Exception
{
public staticvoid main(String args[])
{
intinvalid = 0;
intn, count = 0;
for(int i = 0; i < args.length; i++)
{
try
{
n = Integer.parseInt(args[i]);
}
catch (NumberFormatException e)
{
invalid = invalid + 1 ;
System.out.println("\n Invalid Number: " + args[i]);
}
count = count + 1 ;
}
System.out.println("\n Valid Numbers = " + count);
System.out.println("\n Invalid Numbers = " + invalid);
}
}

javacNumber_Format_Exception.java
java Number_Format_Exception 10 10.75 50 C++ 50.5 15
Output:
Invalid Number: 10.75
Invalid Number: C++
Invalid Number: 50.5
Valid Numbers = 3
Invalid Numbers = 3

Multiple catch statements:
•Itisalsopossibletohavemorethanonecatchstatement
inthecatchblock.
•Whenanexceptioninatryblockisgenerated,theJava
treatsthemultiplecatchstatementslikecasesinaswitch
statement.
•Thefirststatementwhoseparametermatcheswiththe
exceptionobjectwillbeexecuted,andtheremaining
statementswillbeskipped.
•NotethatJavadoesnotrequireanyprocessingofthe
exceptionatall.Onecansimplyhaveacatchstatement
withanemptyblocktoavoidabortion,asshownbelow:
catch(Exceptione);
•Thecatchstatementsimplyendswithasemicolon,which
doesnothing.Thisstatementwillcatchanexceptionand
thenignoreit.

Example:
// This program illustrates the use of the multiple catch statements
class Multiple_Catch
{
public staticvoid main(String args[])
{
try
{
int a = args.length ;
System.out.println(" a = " + a);
int b = 42 / a ;
int c[ ] = {1};
c[42] = 99 ;
}
catch(ArithmeticException e)
{ System.out.println("\n Divide by zero " + e); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(" Array index out of bounds " + e); }
System.out.println(" After the try/catch blocks");
}
}

Use of the finally statement:
•finallystatementisusedtohandleanexception
thatisnotcaughtbyanyofthepreviouscatch
statements.
•finallyblockcanbeusedtohandleanyexception
generatedwithinatryblock.
•Itmaybeaddedimmediatelyafterthetryblockor
afterthelastcatchblock.
•Whenafinallyblockisdefined,thisisguaranteed
toexecute,regardlessofwhetherornotan
exceptionisthrown.
•Thefollowingprogramillustratestheuseofthe
finallystatement.

Example:
// This program illustrates the use of the multiple catch statements
classFinally_Class
{ // Throwing an exception out of the method
static void method1( )
{
try
{
System.out.println("\n Inside method1");
throw new RuntimeException("Example");
}
finally
{ System.out.println("\tfinally block of method1"); }
}
// Return from within a try block
static void method2( )
{
try
{
System.out.println("\n Inside method2");
return ;
}
finally
{ System.out.println("\tfinally block of method2"); }
}

Cont.
// Execute the try block normally
staticvoid method3( )
{
try
{
System.out.println("\n Inside method3");
}
finally
{
System.out.println("\tfinally block of method3");
}
}
public staticvoid main(String args[])
{
try
{
method1( );
}
catch(Exception e)
{
System.out.println("\tException caught");
}
method2( );
method3( );
}
} // End of the class definition

Output:
Inside method1
finally block of method1
Exception caught
Inside method2
finally block of method2
Inside method3
finally block of method3

Cont.
•Inaboveprogram,method1()prematurelybreaksoutof
thetrybythrowinganexception.

•Thefinallyclauseisexecutedonthewayout.
•Themethod2()oftrystatementisexitedviaareturn
statement.
•Thefinallyclauseisexecutedbeforemethod2returns.
•Inthemethod3(),thetrystatementexecutesnormally,
withouterror.
•However,thefinallyblockisstillexecuted.

Throwing own exception:
•Itisalsopossibletothrowourownexceptions.
Thiscanbedonebyusingthekeywordthrowas
follows:
thrownewThrowable_subclass;
•Forexample:
thrownewArithmeticException();
thrownewNumberFormatException();

Example: Program to illustrate the use of throwing an exception
import java.lang.Exception ;
class MyException extendsException
{
MyException(String message)
{ super(message) ; }
}
class User_Exception
{
public staticvoid main(String args[])
{
int x = 5, y= 1000 ;
try
{
floatz = (float)x / (float)y ;
if(z < 0.01)
{
throw newMyException(" Number is too small");
}
}
catch(MyException e)
{
System.out.println("\n Caught my exception");
System.out.println( e.getMessage( ) );
}
finally
{ System.out.println(" I am always here"); }
}
}

Cont.
•Intheaboveprogram,ExceptionisasubclassofThrowableand
thereforeMyExceptionisasubclassofThrowableclass.
•AnobjectofaclassthatextendsThrowablecanbethrownand
caught.

Difference between Throws and
Throw
•Wealreadyknowwecanhandleexceptionsusingtry-
catch block.
Thethrowsdoesthesamethingthattry-catchdoesbut
therearesomecaseswhereyouwouldpreferthrows
overtry-catch.
•For example:
LetssaywehaveamethodmyMethod()thathas
statementsthatcanthroweitherArithmeticExceptionor
NullPointerException,inthiscaseyoucanusetry-catch
asshownbelow

•public void myMethod()
{
try
{
// Statements that might throw an
exception
}
catch (ArithmeticExceptione)
{ // Exception handling statements }
catch (NullPointerExceptione) { // Exception handling
statements
}
}

Cont..
•Butsupposeyouhaveseveralsuchmethods
thatcancauseexceptions,inthatcaseitwould
betedioustowritethesetry-catchforeach
method.Thecodewillbecomeunnecessary
longandwillbeless-readable.
•Onewaytoovercomethisproblemisbyusing
throwslikethis:declaretheexceptionsinthe
methodsignatureusingthrowsandhandlethe
exceptionswhereyouarecallingthismethodby
usingtry-catch.

public void myMethod() throws ArithmeticException, NullPointerException
{
// Statements that might throw an exception
}
public static void main(String args[])
{
try
{
myMethod();
}
catch (ArithmeticException e)
{
// Exception handling statements
}
catch (NullPointerException e)
{
// Exception handling statements
} }

import java.io.*;
class ThrowExample
{
void myMethod(int num)throws IOException, ClassNotFoundException
{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
public class Example1
{
public static void main(String args[])
{ try
{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}
catch(Exception ex)
{
System.out.println(ex);
} } }

Cont..
•Onewaytoovercomethisproblemisbyusing
throwslikethis:declaretheexceptionsinthemethod
signatureusingthrowsandhandletheexceptions
whereyouarecallingthismethodbyusingtry-catch.
•Anotheradvantageofusingthisapproachisthatyou
willbeforcedtohandletheexceptionwhenyoucall
thismethod,alltheexceptionsthataredeclared
usingthrows,mustbehandledwhereyouarecalling
thismethodelseyouwillgetcompilationerror.
Tags