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

Chapter 6-Exception Handling

This document provides an overview of exception handling in Java. It defines what exceptions are and explains that they represent errors or conditions that prevent normal program execution. It describes the keywords try, catch, throw, throws, and finally that are used for exception handling in Java. Specific exception types like ArithmeticException and NullPointerException are also outlined. Examples are provided to demonstrate how to declare exceptions, throw exceptions, write try-catch blocks to handle exceptions, and use the finally clause. The document aims to explain exception handling concepts and best practices in Java.

Uploaded by

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

Chapter 6-Exception Handling

This document provides an overview of exception handling in Java. It defines what exceptions are and explains that they represent errors or conditions that prevent normal program execution. It describes the keywords try, catch, throw, throws, and finally that are used for exception handling in Java. Specific exception types like ArithmeticException and NullPointerException are also outlined. Examples are provided to demonstrate how to declare exceptions, throw exceptions, write try-catch blocks to handle exceptions, and use the finally clause. The document aims to explain exception handling concepts and best practices in Java.

Uploaded by

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

Object Oriented Programming

Computer Engineering Department


AASTU
November, 2021
Chapter 6
Exception Handling

2
Objectives
 To get an of exceptions and exception
overview handling
 To explore the advantages of using
handling
exception
 To declare exceptions in a method header
 To throw exceptions in a method
 To write a try-catch block to handle exceptions
 To explain how an exception is propagated
 To use the finally clause in a try-catch block

3
Introduction
 An exception is an object that represents an error or a condition
that prevents execution from proceeding normally.
 An exception can occur for many different reasons:
 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.
 Handling an exception allows a program to continue executing as
if no problem had been encountered.
 How can you handle the exception so that the program
can continue to run or else terminate gracefully?
 Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.

4
Example: Divide by Zero without Exception
Handling
import java.util.Scanner;
public class DivideByZeroNoExceptionHandling {
public static int quotient(int numerator,int denominator ){
return numerator / denominator;
}// end method quotient
public static void main( String args[] ){
Scanner scanner =new Scanner( System.in ); // scanner for input
System.out.print("Please enter an integer numerator: ");
int numerator = scanner.nextInt();
System.out.print("Please enter an integer denominator: ");
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.print( numerator + " / " + denominator + " = " +
result );
}
}

Output
Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception in thread "main"
java.lang.ArithmeticException: / by zero
5
Introduction(cont’d)
 try
 Contain program statements that you want to monitor for exceptions
 catch
 The exception is caught by the catch block.
 The code in the catch block is executed to handle the exception
 throw
 The execution of a throw statement is called throwing an exception
 The throw statement is analogous to a method call, but instead of calling a
method, it calls a catch block.
 throws
 To declare an exception in a method, use the throws keyword
 finally
 Holds code that absolutely must be executed before a method returns
 A finally block of code always executes, whether or not an exception has
occurred.

6
Exception handling overview
 This is the 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 {
/
/ 7
Exception Types

8
Exception Types(cont’d)
 The exception classes can be classified into three major types:
system errors, exceptions, and runtime exceptions.
 System errors are thrown by the JVM and represented in the
Error class.
 rarely occur.

Class Possible Reason for Exception


LinkageError A class has some dependency on another class,
but the latter class has changed incompatibly
after the compilation of the former class.

VirtualMachineError The JVM is broken or has run out of


the resources it needs in order to continue
operating.

9
Exception Types(cont’d)
 Exceptions are represented in the Exception class,
which describes errors caused by your program and by
external circumstances.

Class Possible Reason for Exception


ClassNotFoundException Attempt to use a class that does not exist.
IOException Related to input/output operations, such as
invalid input, reading past
the end of a file, and opening a nonexistent
file.

10
Exception Types(cont’d)
Runtime exceptions are represented in the RuntimeException
class, which describes programming errors, such as bad casting,
accessing an out-of-bounds array, and numeric errors.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
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.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
ClassNotFoundException Class not found.
InstantiationException Attempt to create an object of an abstract class or interface.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

11
Catching Exceptions(Example)
A method catches an exception using a combination of the try and catch keywords

import java.util.Scanner;
public class QuotientWithException {
public static void main(String[] args)
{ Scanner input = new
Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
if (number2 == 0)
throw new
ArithmeticException("Divis
or cannot be zero");
System.out.println(number1
+ " / " + number2 + " is " +
(number1 / number2));
}
12
catch (ArithmeticException ex)
Example 2
public class CircleWithException {
private double radius;
// Construct a circle with a specified radius
public CircleWithException(double newRadius)
{
setRadius(newRadius);
}
/** Return radius */
public double getRadius() {
return radius;
}

13
Example 2(cont’d)
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException{
if (newRadius >= 0)
radius = newRadius;
else
throw new
IllegalArgumentExc
eption("Radius
cannot be
negative");
}

/** Return the area of this


circle */ public double findArea() {
return radius * radius *
3.14159;
14
Example 2(cont’d)
public class TestCircleWithException
{ public static void main(String[] args)
{
try{
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);

}
catch(IllegalArgumentException ex){
System.out.println(ex);
}
}
}
Output:
java.lang. IllegalArgumentException :
15
Radius cannot be negative
The throws Keyword
 If a method is capable of causing an exception that it
does not handle, it must specify this behavior so that
callers of the method can guard themselves against
that exception.
 You do this by including a throws clause in the
method’s declaration.
 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
}

16
Example
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);
}
}
}
Output:
inside throwOne 17
The finally Keyword
 The finally keyword is used to create a block of code
that follows a try block.
 A finally block of code always executes, whether
or not an exception has occurred.

18
Example
public class ExcepTest{
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{ a
[0]=6;
System.out.println("First element value: "+a[0]);
System.out.println("The finally statement is executed");
}
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException:3
19
First finally
The element value:6 is executed
statement

You might also like