0% found this document useful (0 votes)
24 views

Exception Handling

Uploaded by

Komal Ghorpade
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Exception Handling

Uploaded by

Komal Ghorpade
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Object Oriented Programming -I (3140705)

Unit-06
Exception
Handling

Prof. Jayesh D. Vagadiya


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9537133260
 Outline
Looping

Exception
Using try and catch
Nested try statements
The Exception Class Hierarchy
throw statement
throws statement
Exceptions
 An exception is an object that describes an unusual or erroneous situation.
 Exceptions are thrown by a program, and may be caught and handled by another part of the
program.
 A program can be separated into a normal execution flow and an exception execution flow.
 An error is also represented as an object in Java, but usually represents a unrecoverable
situation and should not be caught.
 Java has a predefined set of exceptions and errors that can occur during execution.
 A program can deal with an exception in one of three ways:
 ignore it
 handle it where it occurs
 handle it at another place in the program
 The manner in which an exception is processed is an important design consideration.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 3


Using try and catch
 Example:
try{ Exception is the superclass of all the
// code that may cause exception exception that may occur in Java
}
catch(Exception e){
// code when exception occurred
}

 Multiple catch:
try{
// code that may cause exception
}
catch(ArithmeticException ae){
// code when arithmetic exception occurred
}
catch(ArrayIndexOutOfBoundsException aiobe){
// when array index out of bound exception occurred
}

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 4


Nested try statements
try
{
try
{
// code that may cause array index out of bound
exception
}
catch(ArrayIndexOutOfBoundsException aiobe)
{
// code when array index out of bound exception occured
}
// other code that may cause arithmetic exception
}
catch(ArithmeticException ae)
{
// code when arithmetic exception occurred
}

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 5


Types of Exceptions
 An exception is either checked or unchecked.
 Checked Exceptions
 A checked exception either must be caught by a method, or must be listed in the throws clause of any
method that may throw or propagate it.
 The compiler will issue an error if a checked exception is not caught or asserted in a throws clause
 Example: IOException, SQLException etc…
 Unchecked Exceptions
 An unchecked exception does not require explicit handling, though it could be processed using try catch.
 The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants.
 Example: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException etc..

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 6


The Exception Class Hierarchy
 Classes that define
LinkageError
exceptions are ArithimaticException
related by VirtualMachineError
inheritance, forming NullPointerException
an exception class Error AWTError
hierarchy. ArrayIndexOutOfBoundExceptio
n
 All error and Throwable Unchecked Exception
IlligalArgumentException
exception classes are
RuntimeException ...
descendents of the Exception
Throwable class AWTException InterruptedIOException
 The custom
exception can be IOException EOFException
created by extending Checked Exception
the Exception class FileNotFoundException
or one of its
...
descendants.
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 7
Java’s Inbuilt Unchecked Exceptions
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 8


Java’s Inbuilt Checked Exceptions

Exception Meaning
ClassNotFoundException Class not found.
IOException Input Output Exceptions
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 9


throw statement
 it is possible for your program to throw an exception explicitly, using the throw statement.
 The general form of throw is shown here:
throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
 Primitive types, such as int or char, as well as non-throwable classes, such as String and
Object, cannot be used as exceptions.
 There are two ways you can obtain a Throwable object:
 using a parameter in a catch clause,
 or creating one with the new operator.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 10


Throw (Example)
public class DemoException {
public static void main(String[] args) {
int balance = 5000;

Scanner sc = new Scanner(System.in);


System.out.println("Enter Amount to withdraw");
int withdraw = sc.nextInt();
try {
if(balance - withdraw < 1000) {
throw new Exception("Balance must be grater than
1000");
}
else {
balance = balance - withdraw;
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 11
The finally statement
public class MainCall {
 The purpose of the finally public static void main(String args[]) {
statement will allow the int balance = 5000;
execution of a segment of Scanner sc = new Scanner(System.in);
code regardless if the try System.out.println("Enter Amount to withdraw");
int withdraw = sc.nextInt();
statement throws an try {
exception or executes if(balance - withdraw < 1000) {
successfully throw new Exception("Balance < 1000 error");
 The advantage of the finally }
else {
statement is the ability to balance = balance - withdraw;
clean up and release }
resources that are utilized in }catch(Exception e) {
the try segment of code that e.printStackTrace();
}
might not be released in finally {
cases where an exception has sc.close();
occurred. }
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 12
throws statement
 A throws statement lists the types of exceptions that a method might throw.
 This is necessary for all exceptions, except those of type Error or RuntimeException, or any
of their subclasses.
 All other exceptions that a method can throw must be declared in the throws clause. If they
are not, a compile-time error will result.
 This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list {
// body of method
}
 Here, exception-list is a comma-separated list of the exceptions that a method can throw.
 Example :
void myMethod() throws ArithmeticException, NullPointerException
{
// code that may cause exception
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 13
Create Your Own Exception
 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 (which is, of course, a subclass of
Throwable).
 The Exception class does not define any methods of its own. It does inherit those methods
provided by Throwable.
 Thus, all exceptions have methods that you create and defined by Throwable.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 14


Methods of Exception class
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed stack trace. This
object can be rethrown.
Throwable getCause( ) Returns the exception that underlies the current exception. If there is no
underlying exception, null is returned.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace, one element at a time, as an
array of StackTraceElement.
Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception as a cause of the invoking
exception. Returns a reference to the exception.
void printStackTrace( ) Displays the stack trace.
void printStackTrace(PrintStream stream) Sends the stack trace to the specified stream.
void setStackTrace(StackTraceElement Sets the stack trace to the elements passed in elements.
elements[ ])
String toString( ) Returns a String object containing a description of the exception.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 15


Custom Exception (Example)
// A Class that represents class MainCall {
user-defined exception static int currentBal = 5000;
class MyException public static void main(String args[]) {
extends Exception try {
{ int amount = Integer.parseInt(args[0]);
public MyException(String s) withdraw(amount);
{ } catch (Exception ex) {
// Call constructor of System.out.println("Caught");
parent (Exception) System.out.println(ex.getMessage());
super(s); }
} }
} public static void withdraw(int amount) throws Exception
{
int newBalance = currentBal - amount;
if(newBalance<1000) {
throw new MyException("Darshan Exception");
}
}
}

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 06 – Exception Handling 16

You might also like