0% found this document useful (0 votes)
2 views47 pages

Module 3 Part I Java SPP

The document provides an overview of exception handling in Java, explaining what exceptions are, how to handle them using keywords like try, catch, throw, and finally, and the difference between checked and unchecked exceptions. It includes examples demonstrating various scenarios of exception handling, including nested try statements and creating custom exceptions. The document emphasizes the importance of handling exceptions to maintain program flow and prevent unexpected terminations.
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)
2 views47 pages

Module 3 Part I Java SPP

The document provides an overview of exception handling in Java, explaining what exceptions are, how to handle them using keywords like try, catch, throw, and finally, and the difference between checked and unchecked exceptions. It includes examples demonstrating various scenarios of exception handling, including nested try statements and creating custom exceptions. The document emphasizes the importance of handling exceptions to maintain program flow and prevent unexpected terminations.
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

Module-3 (Part-I)

Exception Handling

by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon Institute of Technology, Bhubaneswar
Example-1
class test6
{
public static void main(String args[])
{
int a[]={1, 2, 3};
[Link](a[3]);
}
}

No errors at compile time but shows exception at run time


Example-2
class Test {
public static void main(String args[])
{
int d, a;
d = 0;
a = 42 / d;
[Link](a);
}
}

No errors at compile time but shows exception at run time


What is an Exception?
Exception
 An exception is an abnormal condition that arises in a code sequence at
run time.

 In other words, an exception is a run-time error.

 In java, exception is an event that disrupts the normal flow of the


program.
 It is an object which is thrown at runtime.

 The core advantage of exception handling is to maintain the normal


flow of the application.
Exception Handling
 Exception handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, etc.

 Java exception handling is managed via five keywords:


 try
 catch
 throw
 throws
 finally
Cont…
 Program statements that we want to monitor for exceptions are
contained within a try block.

 If an exception occurs within the try block, it is thrown.

 The code can catch this exception using catch block and handle it in
some rational manner
Cont…
 System-generated exceptions are automatically thrown by the Java run-
time system.

 To manually throw an exception, the throw keyword is used.

 Any exception that is thrown out of a method must be specified as such


by a throws clause.

 Any code that absolutely must be executed after a try block completes is
put in a finally block.
General form of an 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 after try block ends
}
Example-1
class Test {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
[Link]("This will not be printed");
}
catch (ArithmeticException e) {
[Link]("Division by zero");
}
[Link]("After catch statement.");
} OUTPUT:
Division by zero
}
After catch statement.
Example-2
class Test {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
[Link]("This will not be printed");
}
catch (ArithmeticException e) {
[Link]("Division by zero“+e);
}
[Link]("After catch statement.");
}
} OUTPUT:
Division by zero [Link] / by zero
After catch statement.
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, two or more catch clauses can be


specified, 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
Example-3: Multiple catch Clauses
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[] = {1};
c[42] = 99;
}
catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}
OUTPUT:
(1) :\> java MultiCatch
a=0
Divide by 0: [Link]: / by zero
After try/catch blocks.

(2) :\>java MultiCatch TestArg


a=1
Array index oob:
[Link]
After try/catch blocks.
Nested try Statements
 The try statement can be nested. That is, a try statement can be inside the
block of another try.
 Example:
class NestTry {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a;
[Link]("a = " + a);
try {
if(a==1)
a = a/(a-a);
if(a==2) {
int c[] = { 1 };
c[42] = 99;
}
}
Cont…
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
[Link]("Divide by 0: " + e);
}
}
Output:
Why to Handle Exceptions?

 The user should handle his/her exceptions because of two reasons:

 it allows you to fix the error

 it prevents the program from automatically terminating


Exception Types
 All exception types are subclasses of the built-in class Throwable.

 Throwable has 2 main subclasses:

 Exception

 Error
The ‘Exception’ sub class
 Exception sub class is used for exceptional conditions that user programs
should catch.

 This is also the class that is subclass to create own custom exception types.

 Example: division by zero


The ‘Error’ Sub class

 Error defines exceptions that are not expected to be caught under normal
circumstances by the program.

 Exceptions of type Error are used by the Java run-time system to indicate
errors at run-time.

 Errors are typically created in response to catastrophic failures that cannot


usually be handled by the program.

Exa: Stack overflow


Using ‘throw’ :
 An exception can be explicitly thrown, using the throw statement.

 General form:
throw ThrowableInstance;

 Here, ThrowableInstance must be an object of type Throwable or a


subclass of Throwable.

 There are two ways to obtain a Throwable object:


using a parameter in a catch clause
or
creating one with the new operator
Cont…
 The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.

 The nearest enclosing try block is inspected to see if it has a catch


statement that matches the type of exception
Example:
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
[Link]("Caught inside demoproc.");
throw e; // rethrow the exception
} }
public static void main(String args[]) {
OUTPUT:
try { Caught inside demoproc.
demoproc(); Recaught:
} [Link]:
demo
catch(NullPointerException e) {
[Link]("Recaught: " + e);
} } }
Using ‘throws’:
 If a method is capable of causing an exception that it does not handle,
 it must specify this behaviour so that callers of the method can guard
themselves against that exception.

 This can be achieved by including a throws clause in the method’s


declaration.

 A throws clause lists the types of exceptions that a method might throw.

 General form:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Example:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
OUTPUT:
try { inside throwOne
throwOne(); caught [Link]: demo
}
catch (IllegalAccessException e) {
[Link]("Caught " + e);
}}
}
Using ‘finally’:
 The keyword finally creates a block of code that will be executed
after a try/catch block has completed and before the code following
the try/catch block.

 The finally block will execute whether or not an exception is thrown

 If an exception is thrown, the finally block will execute even if no


catch statement matches the exception.
Cont…
 Any time a method is about to return to the caller from inside a
try/catch block,
 via an uncaught exception or an explicit return statement,
 the finally clause is also executed just before the method
returns.

 The finally clause is optional. However, each try statement requires


at least one catch or a finally clause.
Example
class FinallyDemo {
static void procA()
{
try
{
[Link]("inside procA");
throw new RuntimeException("demo");
}
finally
{
[Link]("procA's finally");
}
} //end of procA()
static void procB()
{
try
{
[Link]("inside procB");
return;
}
finally
{
[Link]("procB's finally");
}
} //end of procB()
public static void main(String args[])
{
try
{
procA();
}
catch (Exception e)
{
[Link]("Exception caught");
}
procB();
OUTPUT:
} inside procA
} procA’s finally
Exception caught
inside procB
procB’s finally
Java’s Built-in Exceptions:

 Checked Exception

 Unchecked Exception
Checked Exception:

 Checked exception are the exceptions that are checked at compile


time

 The classes which directly inherit Throwable class except


RuntimeException and Error are known as checked exceptions.

 e.g. IOException, SQLException etc.

 If some code within a method throws a checked exception, then the


method must either handle the exception or it must specify the
exception using throws keyword.
Unchecked Exception:

 These exceptions are not checked at compiled time but they are checked at
runtime.

 The classes which inherit RuntimeException are known as unchecked


exceptions

 e.g.: ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.

 In Java exceptions under Error and RuntimeException classes are


unchecked exceptions
Java’s Built-in Exceptions
 Inside the standard package [Link], Java defines several exception
classes
 Example:
Java’s Built-in Exceptions
 Inside the standard package [Link], Java defines several exception
classes
 Example:
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.

 Define a subclass of Exception (which is, of course, a subclass of


Throwable)

 The Exception class does not define any methods of its own. It inherits
those methods provided by Throwable

 Thus, all exceptions, including those that you create, have the methods
defined by Throwable available to them
The Methods Defined by Throwable
toString()
String toString():

 Returns a String object containing a description of the exception.

 This method is called by println( ) when outputting a Throwable object.


Creating Your Own Exception
Subclasses
 Exception defines four public constructors:

1. Exception( )
2. Exception(String msg)

 // Other two support chained exceptions

 The first form creates an exception that has no description.

 The second form lets you specify a description of the exception.


Example
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
Cont…
class ExceptionDemo {
static void compute(int a) throws MyException
{
[Link]("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
public static void main(String args[]) {
try { Output:
Called compute(1)
compute(1); Normal exit
compute(20); Called compute(20)
} catch (MyException e) { Caught MyException[20]
[Link]("Caught " + e);
}
}
}
Chained Exceptions
 Other 2 constructors used for chained exceptions
3. Throwable(Throwable causeExc)
4. Throwable(String msg, Throwable causeExc)

 In the first form, causeExc is the exception that causes the current
exception.
 That is, causeExc is the underlying reason that an exception occurred.

 The second form allows you to specify a description at the same time that
you specify a cause exception
Cont…
 Methods to override for chained exceptions:
 getCause() //refer slide 38 table
 initCause() //refer slide 38 table
Example
class ChainExcDemo
{
static void demoproc()
{

// create an exception
NullPointerException e =new NullPointerException("top layer");

// add a cause
[Link](new ArithmeticException("cause"));

throw e;
}
Cont…
public static void main(String args[])
{
try {
demoproc();
}
catch(NullPointerException e)
{
[Link]("Caught: " + e);

[Link]("Original cause: " + [Link]());


}
}
}
Output:
Caught: [Link]: top layer
Original cause: [Link]: cause
Using Exception

 Exception handling provides a powerful mechanism for controlling


complex programs that have many dynamic run-time characteristics.

 It is important to think of try, throw, and catch as clean ways to


handle errors and unusual boundary conditions in your program’s
logic.

You might also like