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

Topic 4

Exception handling in Java allows programs to gracefully deal with errors and unexpected situations that occur during execution. Exceptions represent problems that disrupt normal program flow. The try-catch block is used to catch exceptions - code that may generate an exception is placed in a try block, and catch blocks handle specific exception types. This allows the program to continue executing rather than terminating due to an error.
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 views54 pages

Topic 4

Exception handling in Java allows programs to gracefully deal with errors and unexpected situations that occur during execution. Exceptions represent problems that disrupt normal program flow. The try-catch block is used to catch exceptions - code that may generate an exception is placed in a try block, and catch blocks handle specific exception types. This allows the program to continue executing rather than terminating due to an error.
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/ 54

CHAPTER 4

Java Exception Handling


Learning Outcomes
✘ At the end of the class, students should
be able to:
✗ Perform concept of exception
handling.
Introduction
✘ A program often encounters problems as
it executes.
✘ It may have trouble reading data, there
might be illegal characters in the data, or
an array index might go out of bounds.
✘ The Java classes Error and Exception
enable programmers to deal with such
problems.
Problem 1
✘ Inspect the following. What went wrong?
C:\cs151\chap80>java Square Enter an integer: rats
Exception in thread "main"
java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source) at
java.util.Scanner.nextInt(Unknown Source) at
java.util.Scanner.nextInt(Unknown Source) at
Square.main(Square.java:12) C:\cs151\chap80>
Exception Hierarchy

also known as IO
Exception
Definition of Exceptions
✘ An exception (or exceptional event) is a problem
that arises during the execution of a program.
When an Exception occurs the normal flow of
the program is disrupted and the program (or
application) terminates abnormally, which is not
recommended, therefore these exceptions are to
be handled.

6
Exception
When an exception
occurs, the Java virtual
Exception is a problem Eg: bad user input, or
machine creates an object
that occurs when a mechanical failure of an
of class Exception which
program is running. I/O device.
holds information about
the problem.

It can then use the


A Java program itself may
Exception object to
catch an exception.
recover from the problem.

7
Exception Scenarios
✘ An exception can occur for many different reasons,
below given are some scenarios where exception
occurs:
✘ A user has entered invalid data.
✘ A file that needs to be opened cannot be found.
✘ A network connection has been lost in the middle of
communications or the JVM has run out of memory.
✘ Noted: Some of these exceptions are caused by user
error, others by programmer error, and others by
physical resources that have failed in some manner.
1-9

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
Error
✘ Error is a problem that occurs when a program is
running.
✗ Eg: Wrong output, abrupt termination of the
program, crashing of the system
✘ Represented by an object of class Error.
✘ But an error is too severe for a program to
handle.
✘ The program must stop running.
Type of Error
✘ Generally, in any language there are two broad
classification of errors:
✘ Compile Time errors
✗ Errors that occur due to wrong syntax in the
program.
✗ Detected by compilers and .class file not created.
✘ Runtime errors
✗ Errors that occur while executing a program.
✗ The .class file are created but may not run
properly.
Problem 2
✘ Are Error objects and Exception objects
related?
Error?
Exception?
Concept of Exception
Handling
✘ Class Exception and class Error both extend
Throwable.
✘ Exceptions are different from Errors because
programs can be written to recover from
Exceptions, but programs can not be written to
recover from Errors.
✘ Exceptions can be caught by a part of the
program that tries to recover from the problem.
Concept of Exception Handling
✘ Hierarchy of Throwable
class
✘ Java exception can be
manually generated
✗ by the code
✗ by the Java runtime
system during the
program execution.
Exception Handling
Mechanism
✘ Exceptions are handled in Java using the
five keywords :
✗ try
✗ catch
✗ throw
✗ throws
✗ finally
Using Exception Handling
✘ To catch an Exception:
try
✗ Put code that might
throw an Exception
inside a try{} block.
✗ Put code that
catch
handles the
Exception inside a
catch{} block. finally
Syntax
try
{
// statements which might throw
// various types of exceptions
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
// Statements following the structure
Try and catch
✘ The statements in the try{} block can include:
✗ Statements that always work.
✗ Statements that might throw an Exception of one type or
another.
✘ One or several catch{} blocks follow the try() block.
✗ Sometimes there can be no catch{} blocks.
✘ Each catch{} block describes the type of Exception it catches.
✗ It does this in a one-item parameter list: ( ExceptionType
parameter )
✗ the parameter is a reference variable that will refer to the
Exception object when it is caught.
Try and catch
Using Exception Handling
✘ If a statement inside the try{} block throws a
InputMismatchException, the catch{} block
immediately starts running.
✘ The remaining statements in the try{} block are
skipped.
✘ After the catch{} block is executed, execution
continues with the statement that follows the catch{}
block.
✘ Execution does not return to the try{} block.
Catching Exceptions
▪ A method catches an exception using a combination of
the try and catch keywords.
▪ A try/catch block is placed around the code that might
generate an exception.
▪ Code within a try/catch block is referred to as protected
code, and the syntax for using try/catch looks like the
following: try
{
// Protected code
} catch(ExceptionName e1)
{
// Catch block
}
Catching Exceptions
✘ The code which is prone to exceptions is placed in the try
block, when an exception occurs, that exception occurred is
handled by catch block associated with it. Every try block
should be immediately followed either by a class block or
finally block.

✘ A catch statement involves declaring the type of exception


you are trying to catch. If an exception occurs in protected
code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much
as an argument is passed into a method parameter.
Catching Exceptions
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);

} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown: " + e);
}
Output:
}
Exception thrown:
}
java.lang.ArrayIndexOutOfBoundsException: 3
class ArrayExcepDemo
{
public static void main(String args[])
{
int var[]={5,10};

try
{
int x = var[2]-var[1];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array subscript
out of range");
}
}
}

Output:
Array subscript out of range
Multiple catch Blocks
✘ A try block can be try {
followed by //Protected code

multiple catch } catch(ExceptionType1 e1) {


//Catch block
blocks. The syntax } catch(ExceptionType2 e2) {
for multiple catch //Catch block

blocks looks like } catch(ExceptionType3 e3) {


//Catch block
the following: }
Multiple catch Blocks
✘ A try block can be try {

followed by
//Protected code
} catch(ExceptionType1 e1) {
multiple catch //Catch block

blocks. The syntax } catch(ExceptionType2 e2) {


//Catch block
for multiple catch } catch(ExceptionType3 e3) {
blocks looks like //Catch block

the following:
}

Note: You can have any number of them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught
there. If not, the exception passes down to the second catch statement. This continues until the exception either is
caught or falls through all catches, in which case the current method stops execution and the exception is thrown down
to the previous method on the call stack.
Multiple catch Blocks
✘ class MultipleCatchDemo


{
public static void main(String args[])
✘ {


try {
int num1 = 30, num2 = 0;
✘ int output = num1 / num2;


System.out.println ("Result = " + output);
}
✘ catch(NumberFormatException e){


System.out.println("NumberFormatException occurred");
}
✘ catch(ArrayIndexOutOfBoundsException e){
✘ System.out.println ("ArrayIndexOutOfBounds occurred");
✘ }
✘ catch(ArithmeticException e){


System.out.println ("ArithmeticException occurred");
} Output:
✘ }

ArithmeticException
} occurred
throws Keywords
✘ If a method does not handle a checked exception, the
method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
✘ throws keyword is used to declare an exception.
✘ You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

public void MethodName() throws Exception


{
// Method implementation

}
throw and throws Statements
✘ throws : to declare code causes an
exception
✗ Can throw more than one exception
✗ Causes the exception throw back to its
caller
✘ throw : create and throw new exception
object

✘ *The keyword to declare an exception is


throws
✘ *The keyword to throw an exception is throw
30
throw and throws Statements

✘ Example Declaring exception

Method1() { Method2() throws Exception {


try{ if (an error occurs){
invoke method2; throw new Exception();
} }
catch (Exception ex) { }
Process exception;
}

Throw exception
Catch exception

31
throw Keywords
✘ throw is used to invoke an exception
explicitly.

public void MethodName() throws Exception


{
// Method implementation
throw new Exception();
}
throw and throws Statements
public class CircleWithException
{
private double radius;

public CircleWithException(double newRadius){


radius = newRadius;
}

public void setRadius(double newRadius) throws RadiusException {


if (newRadius >= 0)
{
radius = newRadius;
} else {
throw new RadiusException("Invalid radius", newRadius);
}
}

public double findArea(){


return radius * radius * 3.142;
}
}

33
finally block
✘ The finally block follows a try block or a
catch block. A finally block of code always
executes, irrespective of occurrence of an
Exception.

✘ Using a finally block allows you to run any


cleanup-type statements that you want to
execute, no matter what happens in the
protected code.
finally block
✘ A finally block appears at the end of
the catch blocks and has the
following syntax:
try {
// Protected code
}
catch(ExceptionType e) {
// Catch block
}
finally {
// The finally block always executes
}
try-catch-finally Statements
✘ The basic way of handling exception in Java
consist of a try block and one or more catch
blocks.

✘ try : contains code for basic algorithm that tells


what to do if everything goes smoothly
✗ try may have code that throw an exception

✘ catch : stops execution and handle the thrown


exception
✗ catch block has parameter

✘ finally : allows programmer to do cleanup code


✗ finally blocks always executes when try block exits

36
finally block
public class FinallyDemo{

public static void main(String args[]){


int a[] = new int[2];
try {
System.out.println("Access element three: " + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown: " + e);
}
finally {
System.out.println("The finally statement is executed");
}
Output:
} Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
} The finally statement is executed
class FinallyDemo {
public static void main(String args[]) {
int a=0,b=5,c=0;
try {
c=b/a;
}

catch(ArithmeticException e) {
System.out.println("I will execute if the exception is
generated");
}
finally {
System.out.println("I always execute at last");
}
}
}
try and catch – Code Example
public class ExceptionDemo2 {
public static void main (String args[]) {

String[] house = {"Gryfindor","Slytherin","Ravenclaw"};

try {
for (int i=0; i < 4; i++) {
System.out.println(house[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception : " + e.toString());
} finally {
System.out.println ("This is always executed");
}
} Gryfindor
} Slytherin
Ravenclaw
Exception :
java.lang.ArrayIndexOutOfBoundsException: 3
This is always executed

39
Exception Categories
1. Checked exceptions
• A checked exception is an exception that occurs at the compile
time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored at the time of compilation,
the Programmer should take care of (handle) these exceptions.

2. Unchecked exceptions
• An Unchecked exception is an exception that occurs at the time
of execution, these are also called as Runtime Exceptions, these
include programming bugs, such as logic errors or improper use of
an API. Runtime exceptions are ignored at the time of compilation.
RuntimeException
Java defines several exception classes inside the standard
package java.lang.

The most general of these exceptions are subclasses of the


standard type RuntimeException. Since java.lang is implicitly
imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.

41
RuntimeException
NumberFormatException
• Invalid conversion of a string to a numeric
format.
ArrayIndexOutOfBoundsException
• Array index is out-of-bounds.
ArithmeticException
• Arithmetic error, such as divide-by-zero.
Common Exception
✘ ArithmeticException
✘ NullPointerException
✘ NegativeArraySizeException
✘ ArrayIndexOutOfBoundsException
✘ SecurityException

43
RuntimeException:
ArrayIndexOutOfBoundsException
class ArrayIndexOutOfBoundsExceptionDemo
{
public static void main(String args[])
{
int a[] = new int[10];
// Array has only 10 elements
a[11] = 9;
}
Output:
} Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at
ArrayIndexOutOfBoundsExceptionDemo.main(ArrayIndexOutOfBoundsExceptionDemo.java:7)
RuntimeException: ArithmeticException
class ArithmeticExceptionDemo
{
public static void main(String args[])
{
int num1 = 30, num2 = 0;
int output = num1 / num2;
System.out.println ("Result = " + output);
}
Output:
} Exception in thread "main" java.lang.ArithmeticException: / by zero
at
ArithmeticExceptionDemo.main(ArithmeticExceptionDemo.java:6)
RuntimeException: NumberFormatException
class NumberFormatExceptionDemo {
public static void main(String args[]){
int num = Integer.parseInt ("XYZ") ;
System.out.println(num);
}
Output:
} Exception in thread "main" java.lang.NumberFormatException: For input string:
"XYZ"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at
NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:5)
Important Notes
✘ A catch clause cannot exist without a try
statement.
✘ It is not compulsory to have finally clauses when
ever a try/catch block is present.
✘ The try block cannot be present without either
catch clause or finally clause.
✘ Any code cannot be present in between the try,
catch, finally blocks.
exceptions are not always
caught but finally always
execute

48
Exercise
1. The exception class is in ____ package
[A] java.file
[B] java.io
[C] java.lang
[D] java.util

2. Which keyword is used to monitor statement for


exception?
[A] try
[B] catch
[C] throw
[D] throws
3.If an exception is generated in try block , then it is caught in ____
block
[A] finally
[B] throw
[C] throws
[D] catch

4. To explicitly throw an exception , ______ keyword is used.


[A] try
[B] catch
[C] throw
[D] throwing

5. ______ is a superclass of all exception classes.


[A] Exception
[B] Throwable
[C] RuntimeException
[D] IOException
6. If a statement tries to divide by zero which
exception is thrown?
[A] ArithemticException
[B] NullPointerException
[C] NumberFormatException
[D] None of these

7. When a method can throw an exception then


it is specified by _____ keyword
[A] finally
[B] throw
[C] throws
[D] catch
8. Which block gets executed compulsory
whether exception is caught or not.
[A] finally
[B] throw
[C] throws
[D] catch

9. When an array element is accessed beyond


the array size , ____ exception is thrown
[A] ArrayElementOutOfLimit
[B] ArrayIndexOutOfBoundsException
[C] ArrayIndexOutOfBoundException
[D] ArrayElementOutOfBounds
10. The classes that extend runtime exception
throw exception called
[A] unchecked Exception
[B] Error
11. Arithmetic Exception is
[A] Checked Exception
[B] Unchecked Exception

12. What is output?


String s="abc";
Integer i=Integer.parseInt(s);
[A] ArithmeticException
[B] NumberFormatException
13. Keyword use for explicitly throw
an exception
[A] throw
[B] throws

14. Can we throw multiple


exception?
[A] yes
[B] no

You might also like