0% found this document useful (0 votes)
35 views31 pages

Kcs-602 Lecture05 Exceptions Cse

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)
35 views31 pages

Kcs-602 Lecture05 Exceptions Cse

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/ 31

Exception Handling

public class ExceptionHello{


public static void main (String[] args) {
int a=20;
int b=0;
System.out.println("Divide=" + (a/b));
}
}

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


at ExceptionHello.main(ExceptionHello.java:5)
Exception Handling

Exception Definition
Exception Occurrence
Exception Handling
Exception Propagation
Exception
• Error occurred in execution time.
• Abnormal termination of program.
• Wrong execution result.
• Java provides an exception handling mechanism in
its language system. Benefits..
– Improve the reliability of application program
– Allow simple program code for exception check and
handling into source
Hierarchical Structure of
Throwable Class
Object

Throwable

Error Exception

... RuntimeException
...

...
Java’s build in Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


Exception Definition
• Treat exception as an object.

• All exceptions are instances of a class extended from


Throwable class or its subclass.

• Generally, a programmer makes new exception class to


extend the Exception class which is subclass of
Throwable class.
Definition of Exception
• Error Class
– Critical error which is not accepted to be caught by our program
under normal circumstances. These types of exception are used
to indicate error by run time environment by the JVM..and thus,
usually cannot be handled by user program. Eg Stack overflow.

• Exception Class consist of exceptional conditions that the user


program should handle.
– Possible exception in normal application program execution
– Eg. Divide by zero, index addressing
Java’s build in Exceptions
• Java.lang package is implicitly imported to all java programs.
Most of the exception derived from RuntimeException are
automatically available. These exceptions thus, do not need to
be included in any method’s throws list. These are called the
unchecked exceptions in Java.

• Five Keywords in java to handle exceptions


– try, catch, throw, throws, and finally
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
}
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their super classes
Java’s build in Exceptions
• IndexOutOfBoundsException :
– When beyond the bound of index in the object which use index, such as
array, string, and vector
• ArrayStoreException :
– When assign object of incorrect type to element of array
• NegativeArraySizeException :
– When using a negative size of array
• NullPointerException :
– When refer to object as a null pointer
• SecurityException :
– When violate security. Caused by security manager
• IllegalMonitorStateException :
– When the thread which is not owner of monitor involves wait or notify
method
Programmer-Defined Exception
Exceptions raised by programmer

• Check by compiler whether the exception handler for


exception occurred exists or not
– If there is no handler, it is error.

• Sub class of Exception class


Exception Definition
class UserErr extends Exception { }
class UserClass {
UserErr x = new UserErr();
// ...
if (val < 1) throw x;
}
Exception Definition
• We can pass the object which contains a message
for the exception in string form

class UserErr extends Exception {


UserErr(String s) super(s); // constructor
}
class UserClass {
// ...
if (val < 1) throw new UserErr("user exception throw message");
}
throw
• The flow of execution stops immediately after the throw
statement, and any subsequent statements are not executed,
it checks weather the programmer has handled the
exception or not, otherwise it prints the stack-trace and
terminates the program.
• All Java’s build in exception have two types of
constructors, one which takes no parameters and other one
which takes string parameter, this string can be used to
define the exception.
throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable or a subclass of
Throwable
Exception Occurrence
• Raised implicitly by system
• Raised explicitly by programmer
– throw Statement Throwable class or
its sub class
throw ThrowableObject;
Exception Occurrence
class ThrowStatement extends Exception {
public static void exp(int ptr) {
if (ptr == 0)
throw new NullPointerException();
}
public static void main(String[] args) {
int i = 0;
ThrowStatement.exp(i);
}
}

java.lang.NullPointerException
at ThrowStatement.exp(ThrowStatement.java:4)
at ThrowStatement.main(ThrowStatement.java:8)
throws
• A method is capable of throwing an exception which is
does not handles.
• throws clause lists the type of exception that a given
method is capable of throwing..except Error and
RuntimeException and their subclasses.
• Type method_name (parameter-list) throws exception-list
{//body of method}
• These exception may not be handled in the causing method
but it will have to be handled by the calling class or
method.
Exception Occurrence
• throws Statement
– When programmer-defined exception is raised,
if there is no exception handler, need to
describe it in the declaration part of method
[modifiers] returntype methodName(params) throws e1, ... ,ek { }

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.
That should be handle by try..catch.. (during call/use )
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
// finally
}
}

inside throwOne
caught java.lang.IllegalAccessException:
demo
Exception Handling
• try-catch-finally Statement
– Check and Handle the Exception

try {
// …
} catch (ExceptionType1 identifier) {
// …
} catch (ExceptionType2 identifier) {
// …
} finally {
// …
}
// Demonstrate finally.
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's
finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's
finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside
procC");
} finally {
System.out.println("procC's
finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception
caught");
}
procB();
procC();
}
}
Café Example
abstract class TemperatureException extends Exception {
private int temperature; // in Celsius
public TemperatureException() {
System.out.println("Temperature exception occurred");
}

class TooColdException extends TemperatureException {


public TooColdException() {
super();
System.out.println("Coffe is too cold");
}
}

class TooHotException extends TemperatureException {


public TooHotException() {
super();
System.out.println("Coffe is too hot");
}
}
Exception

TemperatureException

TooColdException TooHotException
class person{
void drinkCofee (int temperature) throws TooColdException, TooHotException
{
if (temperature <= 65) {
throw new TooColdException();
}
else if (temperature >= 85) {
throw new TooHotException();
}

}
}

class cafe {
public static void main (String [] args)
{

person one=new person();


try
{
one.drinkCofee(70);
System.out.println ("Coffee tasted fine");
}
catch( TooColdException c)
{
System.out.println("Coffee is too cold...warm it again");
}
catch( TooHotException h)
{
System.out.println("Coffee is too hot...bring it after some time");
}
finally
{
System.out.println("Person Left");
}

}}
Coffee tasted fine
70 Person Left

Temperature exception occurred


Coffe is too cold
50 Coffee is too cold...warm it again
Person Left

Temperature exception occurred


Coffe is too hot
90 Coffee is too hot...bring it after some time
Person Left
throw throws
throws keyword is used to declare
throw keyword is used to throw an
one or more exceptions, separated by
exception explicitly.
commas.

Only single exception is thrown by Multiple exceptions can be thrown


using throw. by using throws.

throw keyword is used within the throws keyword is used with the
method. method signature.

Syntax wise throw keyword is Syntax wise throws keyword is


followed by the instance variable. followed by exception class names.

Checked exception cannot be For the propagation checked


propagated using throw exception must use throws keyword
only.Unchecked exception can be followed by specific exception class
propagated using throw. name.
throw throws

Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

Checked exception cannot be Checked exception can be


propagated using throw only. propagated with throws.

Throw is followed by an instance. Throws is followed by class.

Throws is used with the method


Throw is used within the method.
signature.

You can declare multiple exceptions


You cannot throw multiple e.g.
exceptions. public void method()throws
IOException,SQLException.

You might also like