0% found this document useful (0 votes)
6 views45 pages

Module 2 - Exception Handling

Uploaded by

parmar2100parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views45 pages

Module 2 - Exception Handling

Uploaded by

parmar2100parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

PMCA502L Java Programming

Exception Handling

Thilagavathi M
SCORE
Difference between Error and Exception
Error Exception

Any departure from the expected behaviour Any error or problem which a programmer or an
of the system or program, which stops the application can handle and continue to work
working of the system and cannot be handled normally.
at the application level but only at the system
level.

Errors are always unchecked. Exceptions may be checked or unchecked


(Example) exceptions.
'Out of Memory' error, 'Stack overflow', which
can only be handled by the OS.

Errors cannot be thrown, caught or created. Exceptions can be created manually by the
Even if an 'OutofMemory' error is caught the programmer, thrown or caught.
user will not be in a position to fix it, as it
depends on OS, architecture and server
configuration.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Exceptions can be
• Checked Exceptions
• Unchecked Exceptions

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Difference between Checked and Unchecked
Exceptions

Checked Exceptions Unchecked Exceptions

Exceptions which should either be handled or The compiler ignores these exceptions and
registered that these may be thrown from hence there will not be any compilation error,
the method under consideration, so that the even if these exceptions are not handled or if
caller of this method can handle these these exceptions are not intimated to the caller
exceptions. Otherwise, the program will not of the method in which these exceptions arise.
compile.

Also called compile time exception. Also called runtime exception.

Example: Example:
IOException, FileNotFoundException, etc. ArrayIndexOutOfBoundsException,
These exceptions should be handled or ArithmeticException, etc.
forwarded to the caller. Else, compilation These exceptions do not stop the program from
error will be generated. being compiled successfully even if they are not
properly handled.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Exception Handling
• Handled through 5 keywords
 try
 catch
 throw
 throws
 finally

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Exception
• It is an object that is created when an
abnormal situation arises in the
program.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Advantages
• Allows the programmer to fix the error and thus
prevents the program from automatically terminating.
Once the exceptions are handled, the program can
resume execution from then onwards.
• It separates the code that deals with errors from the
code needed for the program logic. Hence, it increases
readability.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Exception Handling

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Sub-classes of Runtime Exception
1) ArithmeticException
2) ArrayStoreException
3) IndexOutOfBoundsException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
4) IllegalArgumentException
 NumberFormatException
& several other subclasses including
5) NoSuchElementException
 InputMismatchException
6) NullPointerException
7) ClassCastException
...

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Compile Time Exception
• IOException
• ClassNotFoundException
• EOFException
• FileNotFoundException
• InterruptedException
• NoSuchFieldException
• NoSuchMethodException

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Example to show what happens when
an exception is caused.
class SampleException
{
public static void main(String args[ ])
{
int a =args.length;
int b = 10;
double c = b/a; Stmt (I)
System.out.println(c);
}
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Output
When the program is executed as
java SampleException

a‘s value will be 0.

Therefore, when Stmt (I) is executed

Exception in thread "main" java.lang.ArithmeticException:/by zero


at SampleException.main(SampleException.java:7)

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
• When the program is modified to include a method, in which
the exception is caused:
class SampleException
{
static void method1( )
{
int a = 0;
int b = 10;
double c = b/a;
System.out.println(c);
}
public static void main(String args[ ])
{
method1( );
}
}
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Output
Exception in thread "main" java.lang.ArithmeticException:/by zero
at SampleException.method1(SampleException.java:7)
at SampleException.main(SampleException.java:12)

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
method1()

main()

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Syntax
try
{
...
}
catch(Exceptiontype1 e1)
{
...
}
catch(Exceptiontype2 e2) //optional
{
...
}
finally //optional
{
//code bock to be executed after the try block ends
}
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
class SampleException
{
public static void main(String args[ ])
{
int a = args.length;
int b = 10;
try
{
double c = b/a;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
c = 0;
}
System.out.println(c);
} PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
}
Methods defined by 'Throwable' class
• String getMessage( )

• a) void printStackTrace( )
b) void printStackTrace(PrintStream ps)

• String toString( )

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
class SampleException
{
public static void main(String args[ ])
{
int a = args.length; int b = 10;
try
{
double c = b/a;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage( ));
System.out.println(e);
e.printStackTrace( );
c = 0;
}
System.out.println(c);
} PMCA502L: Thilagavathi M,
} AP(Sr.), SCORE
Rules for using try-catch block
1) The parameter of catch block must be of type
Throwable or one of its subclasses. If the class
specified here has subclasses, the catch block will be
expected to process exceptions of that class + all its
subclasses.
Example: catch(Exception e)
{
...
}
2) The try block must be surrounded by curly braces
and cannot be used on a single statement.
try
System.out.println(args[0])  not valid

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Rules for using try-catch block
3) Variables declared in a try block are only available within that
block. The catch block itself is a separate scope from the try block.
Example: try
{
int x = 10;
...
}
catch(Exception e)
{
System.out.println(x);
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Rules for using try-catch block
4) A 'catch' statement cannot catch an exception thrown by
another try statement.
Example: try
{
System.out.println(1 / 0);
}
catch(ArrayIndexOutOfBoundsException e)
{
...
}

5) try-catch blocks are bonded together. If 'try' is embedded within


a loop, catch also should be embedded inside that loop.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Rules for using try-catch block
6) Must not include other code between a try block and its catch
blocks or between the catch blocks and the finally block.
Example: try
{
...
}
x = y + z;
catch(. . .)
{
...
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Rules for using try-catch block
7) A method can have a single try block followed by all the catch
blocks for the exceptions that need to be processed in the method.
try
{
...
}
catch(ArithmeticException e)
{
...
}
catch(ArrayIndexOutOfBoundsException e)
{
...
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Rules for using try-catch block
8) While defining multiple catch blocks, the most derived types
should be placed first and the most basic type last. Otherwise the
code will not compile.
i.e. Exception sub classes must come before any of their super
classes, since a catch statement that uses a superclass will catch
exceptions of that type + any of its subclasses.

A subclass would never be reached if it comes after its super class.


In Java, unreachable code is an error.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Example – Unreachable Code Error
class supersubcatch
{
public static void main(String[] args)
{
try
{
int a=0, b=42/a;
}
catch(Exception e)
{
System.out.println("I will catch all exceptions");
}
catch(ArithmeticException e)
{
System.out.println("Never reached");
}
}
}
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
To illustrate
ArrayIndexOutOfBoundsException
public class ArrayIndex
{
public static void main(String args[ ])
{
try
{
int[ ] a={10, 20, 30};
a[10]=5;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Give an index within the range");
System.out.println(e);
}
}
PMCA502L: Thilagavathi M,
} AP(Sr.), SCORE
NullPointerException
public class nullpointer
{
public static void main(String args[ ])
{
char c;
String s;
try
{
c = s.charAt(0);
}
catch(NullPointerException e)
{
System.out.println("You have not yet assigned any text to s");
c = "A";
}
PMCA502L: Thilagavathi M,
} } AP(Sr.), SCORE
NumberFormatException
public class numberformat
{ public static void main(String args[ ])
{
try
{
String input = "VIT";
int x = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println(e.getMessage( ));
x = 10;
}
System.out.println(x+100);
}
PMCA502L: Thilagavathi M,
} AP(Sr.), SCORE
Multiple Catch
class multicatch catch(NumberFormatException e)
{ {
p.s.v.m(String args[ ]) System.out.println(e);
{ n = 10;
String s; int n; }
try System.out.println(n*10);
{ }
s = args[0]; }
n=Integer.parseInt(s);
}
catch(ArrayIndexOutOfBounds
Exception e)
{
S.o.p (e.getMessage( ));
s="10";
n=Integer.parseInt(s);
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Multiple Catch
• The 2 separate catch blocks can also be written as a single catch
block as follows:

catch(ArrayIndexOutOfBoundsException | NumberFormatException e)

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Multiple try
• Java provides the flexibility of having as many try blocks as we
want.

class multicatch try


{ {
public static void main(String[] args) n=Integer.parseInt(s);
{ }
String s; int n; catch(NumberFormatException e)
try {
{ System.out.println(e);
s = args[0]; n = 10;
} }
catch(ArrayIndexOutOfBoundsException e) System.out.println(n*10);
{ }
System.out.println(e); }
s="10";
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
throw
Need for throwing the exception manually:
• The calling program may need to know about the
exception that had occurred in the called method. If
the exception that has been caught has to be
passed to the calling program, it can be re-thrown
from within the catch block using a throw
statement.
• Useful to throw user defined exceptions.
• Syntax:
throw throwableInstance;
• Two ways to obtain a throwable object:
 Using the parameter in the catch clause.
 Creating a new one with the new operator.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Constructors of Throwable class & its
subclasses

• Throwable( )
 Creates an Exception that has no description.
• Throwable(String msg)
 Let’s us to specify a description of the exception. This
string is displayed when the object is used as an argument to
the println( ).
•  To create a new NullPointerException object, the syntax is,
new NullPointerException( );
(or)
new NullPointerException("The string is empty");
• To throw a NullPointerException, the syntax is,
throw new NullPointerException( )
(or)
NullPointerException NP = new NullPointerException( );
throw NP;

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Example
public static void main(String args[ ])
class throwSample {
{ try
static void method1( ) {
{ method1( );
try }
catch(ArithmeticException e)
{ {
throw new S.o.p("Caught inside main" + e);
ArithmeticException("thrown explicilty"); }
} }
catch(ArithmeticException e) }
Output:
{ Caught inside method1
S.o.p("Caught inside method1"); Caught inside main
throw e; java.lang.ArithmeticException:
} thrown explicitly
}

35
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
throws
• Syntax:
returntype nameofthemethod(parameters) throws exceptionlist
{
...
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
throws Example
class throwsexample
{
static void method1( ) throws ArithmeticException
{
System.out.println(10/0);
}
public static void main(String[ ] args)
{
try
{
method1( );
}
catch(Exception e)
{
System.out.println("Caught");
}
} PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
}
throws Example
class throwsexample
{
static void method1( ) throws IOException
{
int a=10, b=2, c;
c = a / b;
throw new IOException( );
}
public static void main(String[ ] args)
{
try
{
method1( );
}
catch(IOException e)
{
System.out.println(e);
}
} PMCA502L: Thilagavathi M,
} AP(Sr.), SCORE
finally
• Used when some particular code is to be run before
a method returns, no matter whether exceptions
are thrown within the try block or not.

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
finally
try block executes normally without errors.
void method1( )
{
try
{
System.out.println("Hello");
}
finally
{
System.out.println("in finally block");
}
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
finally
When a method gives up the program control by throwing an
exception.
void method1( )
{
try
{
throw new RuntimeException("sample");
}
finally
{
System.out.println("in finally block");
}
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
finally
A try statement is exited via a return statement. Still finally clause
is executed before the method returns.
void method1( )
{
try
{
return;
}
finally
{
System.out.println("in finally block");
}
}

PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Creating user-defined Exceptions
• To handle situations specific to our applications, our
own exceptions can be created by extending the
predefined Exception Classes.
• The methods defined in Throwable class will be
available for user created exceptions also.
• Steps
• Step I: First create a new Exception Class with a name by
extending the predefined Exception classes. Override the
methods of Throwable class if needed.
• Step II: If any statement in the program tries to throw an
exception, there throw an object of this newly created
Exception.
• Step III: Provide necessary exception handling mechanism to
handle this or forward it using 'throws' clause. Remember,
forwarding should be explicitly done only when the user
defined exception extends checked exception. If it extends an
unchecked exception, 'throws' clause is not compulsory.
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
Example
class cgpamain
class CGPAException extends Exception {
{ p s v m(String args[ ]) throws CGPAException
public String toString( ) {
{ float cgpa;
return "Exception:InvalidCGPA"; Scanner sc=new Scanner(System.in);
cgpa=sc.nextFloat();
} if(cgpa<0.0f || cgpa>10.0f)
} throw new CGPAException();
System.out.prinln("valid cgpa");
}
}

44
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE
using try-catch block
public static void main(String args[ ])
{
float cgpa;
Scanner sc=new Scanner(System.in);
cgpa=sc.nextFloat();
try
{
if(cgpa<0.0f || cgpa>10.0f)
throw new CGPAException();
System.out.prinln("valid cgpa");
}
catch(CGPAException e)
{
System.out.println(e);
}
}
PMCA502L: Thilagavathi M,
AP(Sr.), SCORE

You might also like