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

Exception Handling

Uploaded by

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

Exception Handling

Uploaded by

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

OBJECT ORIENTED PROGRAMMING

LAB 5

EXCEPTION HANDLING
CONCEPTS OF EXCEPTION HANDLING
 Exception is an abnormal condition that arises in the code sequence. It can be anything which
interrupts the normal flow of the program.
 There can be several reasons for an exception. For example, following situations can cause an
exception:
– Opening a non-existing file, Network connection problem, Operands being manipulated are
out of prescribed ranges, class file missing which was supposed to be loaded and so on.
 In the programming languages that do not support exception handling, errors must be checked
and handled manually, usually through the use of error codes.
 In contrast, Java:
 Provides syntactic mechanisms to signal, detect and handle errors
 Ensures a clean separation between the code executed in the absence of errors and the
code to handle various kinds of errors
 Brings run-time error management into object-oriented programming

 Benefits of Exception Handling:


 Separating Error-Handling code from “regular” business logic code
 Grouping and differentiating error types.
 Propagating errors up the call stack
CONCEPTS OF EXCEPTION HANDLING CONT
1. The term "exception" means "exceptional condition" and is an occurrence that alters the normal
program flow.
2. Things like hardware failures, resource exhaustion , bugs etc can lead to exceptions.
3. When an exceptional event occurs in java, an exception is said to be "thrown".
4. The code that's responsible for doing something about the exception is called an "exception
handler", and it "catches" the thrown exception.
5. Exception handling works by transferring the execution of a program to an appropriate exception
handler when an exception occurs.
6. We need a way to tell the JVM what code to execute when a certain exception happens. To do
this, we use the try and catch keywords.
7. The try is used to define a block of code in which the exceptions may occur.
8. This block of code is called a guarded region.
9. One or more catch clauses match a specific exception (or a group of exceptions) to a block of
code that handles it.
10. Once the control jumps to the catch block, it never returns to complete the balance of the try
block.
EXCEPTIONS IN JAVA
• “Throwable” is the super class in exception hierarchy.
• Exceptions may occur during compile time or run time.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
EXCEPTION CLASSES

 In Java, exceptions are objects. When you throw an exception, you throw an object. However
-- You can't throw just any object as an exception, only those objects whose classes descend
from Throwable.

 Throwable serves as the base class for an entire family of classes, declared in java.lang, that
your program can instantiate and throw.

 Throwable has two direct subclasses, Exception and Error.

 Exceptions are thrown to signal abnormal conditions that can often be handled by some
catcher, though it's possible they may not be caught and therefore could result in a dead
thread.

 Errors are usually thrown for more serious problems, such as OutOfMemoryError, that may
not be so easy to handle. They usually indicate errors with the runtime environment;
user programs are not supposed to catch them. In general, code you write should throw only
Exceptions, not Errors.

 Errors are usually thrown by the methods of the Java API, or by the Java virtual machine
itself.
EXCEPTIONS AND ERRORS

 Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.

 Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.
 Few examples –
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
HIERARCHY OF EXCEPTION CLASSES
EXCEPTION SOURCES

 Exceptions can be:


1) Generated by the Java run-time system: Fundamental errors that violate the rules
of the Java language or the constraints of the Java execution environment.

2) Manually generated by programmer’s code:Such exceptions are typically used to


report some error conditions to the caller of a method.
EXCEPTION HANDLING
 An exception is an object that describes an exceptional condition (error) that has occurred
when executing a program.

 Exception handling involves the following:


1) When an error occurs, an object (exception) representing this error is created/instantiated
in the method that caused it and thrown.
2) That method may choose to handle the exception itself or pass it on
3) either way, at some point, the exception is caught and processed.

 Five constructs are used in exception handling:


1) try – a block surrounding program statements to monitor for exceptions
2) catch – together with try, catches specific kinds of exceptions and handles them in some
way
3) finally – specifies any code that absolutely must be executed whether or not an exception
occurs
4) throw – used to throw a specific exception from the program
5) throws – specifies which exceptions a given method can throw
EXCEPTION-HANDLING BLOCK
General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }
where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the exception Exception
3) finally { … } is the block of code to execute before the try block ends

Note: If a catch block handles multiple exceptions, you can separate them using a pipe (|)
EXAMPLE : 1
class Excl
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Excl.main(Excl.java:6)

//Demonstrate handling pre-defined exceptions using try-catch


class Excl1 {
public static void main(String args[])
{
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e){ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

Output:
Division by zero.
After catch statement.
EXAMPLE : 2
// Handle an exception and move on with the rest of the program
class HandleError
{
public static void main(String args[])
{
int a=12345, b=0;
for(int i=10; i>-5; i--)
{
try
{
b = a / i;
System.out.println(b);
}
catch (ArithmeticException e)
{
System.out.println("Division by zero."); // to print your custom message
System.out.println("Exception: " + e); // to print system generated error
message
a = 1234; // set a to 1234 and continue
}
}
System.out.println("This is continuation of the program");
}
}
EXAMPLE : 3
// Demonstrate multiple catch statements
class MultipleCatches
{
public static void 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("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bound: " + e);
}
System.out.println("After try/catch blocks.");
}
}

>java MultipleCatches
>java MultipleCatches 5
CATCH MULTIPLE DIFFERENT EXCEPTIONS IN THE SAME CATCH BLOCK

From Java 7 it was made possible to catch multiple different exceptions in the same catch block

// Demonstrate multiple exception in single catch block


class MultipleCatches
{
public static void 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 | ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("After try/catch blocks.");
}
}


EXAMPLE : 4
// Demonstrate multiple catch statements, order of catch blocks
/* This program contains an error. A Sub-class must come before its Super-class in a series of catch statements. If not,
unreachable code will be created and a compile-time error will result.*/

class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) // ERROR - unreachable
{
System.out.println("This is never reached.");
}
}
}

SuperSubCatch.java:20: error: exception ArithmeticException has already been caught


catch(ArithmeticException e) { // ERROR – unreachable
EXAMPLE : 5
// An example for nested try statements
class NestTry
{
public static void main(String args[]) {
try {
int a = args.length; // try a=0, a=1 and a=2 as well
int b = 42 / a; //This statement will generate a divide-by-zero exception if a=0.
System.out.println("a = " + a);

try // nested try block


{
/* If a=1, then an divide-by-zero exception will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero

/* If a=2 then generate an out-of-bounds exception. */


if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}

}
catch(ArithmeticException e){
System.out.println("Divide by 0: " + e);
}
}
}
>java NestTry
>java NestTry 1
>java NestTry 1 2
THROWING EXCEPTIONS(THROW)
 So far, we were only catching the exceptions that are automatically thrown by the Java
system.
 A user program may throw an exception explicitly:
throw ThrowableInstance;
 ThrowableInstance must be an object of type Throwable or its subclass.
 Once an exception is thrown by:
throw ThrowableInstance;
1)The flow of control stops immediately.
2) The nearest enclosing try statement is inspected if it has a catch statement/block that
matches the type of exception:
 If one exists, control is transferred to that block
 otherwise, the next enclosing try statement is examined
 If no enclosing try statement has a corresponding catch clause, the default exception handler halts
the program and prints the stack
EXAMPLE : 6
// Demonstrate use of throw
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
e.printStackTrace();
}
}
}
FINALLY CLAUSE

 When an exception is thrown:


1) the execution of a method is changed
2) the method may even return prematurely.
 This may be a problem is many situations.
 For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the
proper closure of the file.
 The finally block is used to address this problem.
 The try/catch statement requires at least one catch or finally clause, although both are optional:
try { … }
catch(<ExceptionType1> <objName>) {<handler if ExceptionType1 occurs> … } …
catch(<ExceptionTypeN> <objName>) {<handler if ExceptionTypeN occurs> … }
finally { … }
 Executed after try/catch whether of not the exception is thrown.
 Any time a method is to return to a caller from inside the try/catch block via:
1) uncaught exception or
2) explicit return
the finally clause is executed just before the method returns.
FINALLY CLAUSE CONT
1. We use finally when we need to clean up after an exception occurs.
2. Because execution transfers out of the try block as soon as an exception is thrown, we can't put cleanup code at the bottom of
the try block and expect it to be executed if an exception occurs.
3. Exception handlers are poor places to clean up after the code in the try block, because each handler then requires its own copy
of the cleanup code. lots of redundant code. To address this problem java offers the finally block.
4. A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not.
5. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and
before the return executes.
6. This is the right place to close your files, release your network sockets, and perform any other cleanup your code requires.
7. If the try block executes with no exceptions, the finally block is executed immediately after the try bock is completes.
8. If there was an exception thrown, the finally block executes immediately after the proper catch block completes.

** finally always runs


if an exception is thrown finally runs
if an exception is not thrown finally runs
if an exception is caught, finally runs
if an exception is not caught, finally runs
USAGE OF TRY-CATCH , FINALLY STATEMENTS
1. If you have one or more Catch Blocks they must immediately follow the Try Block.
2. The Catch Blocks must all follow each other, Without any other Statements or Blocks in
between.
3. The Order In which the Catch Blocks appear Matters.
4. It is illegal to use a try clause without either catch block or a finally clause. A try clause by itself
will result in a compiler error.
5. It is legal to omit either the catch block or the finally clause, but not both.
6. Any catch clause must immediately follow the try block.
7. Any finally clause must immediately follow the last catch block(or must immediately follow the
try block if there is no catch).
8. You can't insert any code in between the try, catch or finally blocks.
SYNTAX
try
{
// this is the first line of the guarded region that is governed by the try
//keyword. Put code here that might cause some kind of exception we may
//have many code lines here or just one
}
catch(MyFirstException ex1)
{
// put code here that handles this exception.
}
catch(MySecondException ex2)
{
// put code here that handles this exception.
}
finally
{
// put code here to release any resource we allocate in the try clause.
}
>> When an object of a subtype of Exception is thrown, it must either be handled or declared.
>> These objects are called checked exceptions, and include all exceptions except those that are subtypes of
RuntimeException, which are unchecked exceptions.
EXAMPLE : 7
// Demonstrate finally
public class TestFinally
{
public static void main(String[] args)
{
test();
}
public static void test()
{
try
{
throw new NullPointerException("NPE");
}
catch(Exception e)
{
System.out.println("NullPointerException");
}
finally
{
System.out.println("finally");
}
}
}
EXAMPLE : 8
// Demonstrate finally during return
public class DemoFinally
{
public static void main(String[] args)
{
System.out.println(test());
}
public static String test()
{
try
{
throw new NullPointerException("NPE");
}
catch(Exception e)
{
return "Null Pointer Exception Finally";
}
finally
{
System.out.println("finally");
}
}
}
HIERARCHY OF EXCEPTION CLASSES
JAVA BUILT-IN EXCEPTIONS
 The default java.lang package provides several exception classes.
 Two sets of built-in exception classes in Java:
1) unchecked exceptions – the compiler does not check if a method handles or throws these
exceptions
2) checked exceptions – must be included in the method’s throws clause if the method
generates but does not handle them.
CHECKED VS UNCHECKED EXCEPTION
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during
compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the
program, it will give compilation error.
Examples of Checked Exceptions :-
ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has
handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not check to see if a method
handles or throws these exceptions.
Examples of Unchecked Exceptions:-
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.
UNCHECKED BUILT-IN EXCEPTIONS
Methods that generate but do not handle those exceptions need not declare them in the
throws clause:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. ArrayStoreException
4. ClassCastException
5. IllegalStateException
6. IllegalMonitorStateException
7. IllegalArgumentException
8. StringIndexOutOfBounds
9. UnsupportedOperationException
10. SecurityException
11. NumberFormatException
12. NullPointerException
13. NegativeArraySizeException
14. IndexOutOfBoundsException
15. IllegalThreadStateException
CHECKED BUILT-IN EXCEPTIONS
Methods that generate but do not handle those exceptions must declare them in the throws
clause:
1. NoSuchMethodException
2. NoSuchFieldException
3. InterruptedException
4. InstantiationException
5. IllegalAccessException
6. CloneNotSupportedException
7. ClassNotFoundException
BUILT-IN EXCEPTIONS
THROWS DECLARATION
 If a method is capable of causing an checked exception that it does not handle, it must specify
this behavior by the throws clause in its declaration:
type name(parameter-list) throws exception-list
{

}

 where exception-list is a comma-separated list of all types of exceptions that a method might
throw.

 All exceptions must be listed except Error and RuntimeException or any of their subclasses,
otherwise a compile-time error occurs.
EXAMPLE : 9
// Demonstrate throws
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);
}
}
}
(OR)
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("Demo");
}
public static void main(String args[]) throws IllegalAccessException
{
throwOne();
}
}
EXAMPLE 10: USER DEFINE EXCEPTION/ CUSTOM
EXCEPTION
 A new exception class is defined, with a private variable: detail, a one parameter constructor and an
overridden toString method:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
The static compute method throws the MyException exception whenever its a argument is greater than 10:
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if (a > 10) throw new MyException(a);
System.out.println("Normal exit");
}
EXAMPLE-10: USER DEFINE EXCEPTION CONT..

The main method calls compute with two arguments within a try block that catches the MyException exception:

public static void main(String args[])


{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
EXAMPLE-11: CHAINING OF EXCEPTIONS
Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of
another exception.
// Demonstrate exception chaining.
class ChainExcDemo
{
static void demoproc()
{
NullPointerException e = new NullPointerException("top layer"); // create an exception

e.initCause(new ArithmeticException("cause")); // add a cause


throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Caught: " + e); // display top level exception
System.out.println("Original cause: " + e.getCause()); // display cause exception
}
}
}
LAB EXERCISE :

Write a Java program to find factorial of given n numbers. Read the value of n as a command line
Argument and read the n integers using Scanner class.

Throw multiple user-defined exceptions and define multiple catch statements to handle them:
NotAnIntegerException : If user gives any other input rather than integers the application
must this user defined exception.

NegativeNumberException: If the user gives a negative integer as input the application must
throw this user defined exception.

OutOfMemoryException: If the user gives an integer greater than 16 as input the application
Must throw this user defined exception.

Write a finally block to display the end of the process.

Continue taking the input until n legal inputs are given.


EXPECTED OUTPUT:

$ java TestFactorial 5

Enter an integer:0
Factorial of 0 is: 1

Enter an integer:1
Factorial of 1 is: 1

Enter an integer:5
Factorial of 5 is: 120

Enter an integer:-4
NegativeNumberException[-4]

Enter an integer:16
Factorial of 16 is: 2004189184

Enter an integer:18
OutOfMemoryException[18]

Enter an integer:h
Not An Integer Exception

Enter an integer:7
Factorial of 7 is: 5040
End of Execution
PRE LAB QUESTIONS

1. What is the difference between throw and throws keyword in Java?


2. What is the difference between final, finally and finalize in Java?
3. Differentiate between Error and Exception in Java.
4. There are three statements in a try block – statement1, statement2 and statement3. The try block
is followed by a catch block to catch the exceptions occurred in the try block. Assume that
exception has occurred in statement2. Does statement3 get executed or not? Justify.
5. What is unreachable catch block error?
6. Differentiate between checked and unchecked exceptions in Java.
7. Does finally block get executed If either try or catch blocks are returning the control?
8. Can we keep the statements after finally block If the control is returning from the finally block
itself ?
9. List at least 5 methods of the Throwable class in Java along with their signature and purpose.
10. What are chained exceptions in Java?
11. What are the legal combinations of try, catch and finally blocks in Java?
12. What is the purpose of printStackTrace( ) method?
REFERENCES

1. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/module-summary.html
2. https://www.javatpoint.com/java-tutorial
3. https://www.tutorialspoint.com/java/java_documentation.htm
4. https://in.udacity.com/course/java-programming-basics--ud282
5. https://www.youtube.com/channel/UCElB8X42691dD9R6xVTDLkw
6. Herbert Schildt, The Complete Reference Java, 7th Edition, Tata McGraw Hill, 2006.

You might also like