[go: up one dir, main page]

0% found this document useful (0 votes)
6 views39 pages

Chapter - 4 Exception Handling

Uploaded by

teddytadesse490
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)
6 views39 pages

Chapter - 4 Exception Handling

Uploaded by

teddytadesse490
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/ 39

Exception Handling

Writing Robust Java Codes

Object Oriented Programming - CoSc2051 1


Chapter Outlines
 Exceptions Overview
 Catching Exceptions
 The finally Block
 Exception Methods
 Declaring Exceptions
 Defining and Throwing Exceptions
 Errors and Runtime Exceptions

Object Oriented Programming - CoSc2051 2


Introduction to Exception Handling
 Exception handling enables a program to deal with exceptional
situations and continue its normal execution.
 Two cases exist when you design & code a program.
– The case where nothing unusual happens and
– The case where exceptional things happen.
 An exception is an object that represents an error or a condition
that prevents execution from proceeding normally.
 If the exception is not handled, the program will terminate
abnormally.
 How can you handle the exception so that the program can continue
to run or else terminate gracefully?

Object Oriented Programming - CoSc2051 3


Introduction to Exception Handling
 Examples of exception:
 E.g., Array out of bounds, Division by zero, etc.
 Exception handling enables programmers to create applications
that can resolve exceptions.
 Exception-Handling Overview:
 Exceptions are thrown from a method.
 The caller of the method can catch and handle the exception.
 Look below example which reads in two integers and displays their
quotient.

Object Oriented Programming - CoSc2051 4


Introduction to Exception Handling
• public classdetects
A method Quotient {
an error and throws an exception
public static void main(String[] args) {
– Exception
Scanner input handler processes the error
= new Scanner(System.in);
• The error is considered caught and handled in this model
// Prompt the user to enter two integers
• System.out.print("Enter two integers:
Code that could generate errors ");
put in try blocks
int number1 = input.nextInt();
Code for=error
int– number2 handling enclosed in a catch block
input.nextInt();
– The finally always executes with or without an error
System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
• Keyword throws tells exceptions of a method
}
•} Termination model of exception handling
– The block in which the exception occurs expires

Object Oriented Programming - CoSc2051 5


Introduction to Exception Handling
 In Java, there is a way to deal with cases where exceptional things can
happen.
– The way is known as exception handling.
 It deals with methods that have some special case that is handled
differently depending on how the method is used.
– Example: a method that handles division by zero.
 Handles errors

Object Oriented Programming - CoSc2051 6


Recap
1. What is the output of the following code?
public class Test {
public static void main(String[] args) {
try {
int value = 30;
if (value < 40)
throw new Exception("value is too small");
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("Continue after the catch block");
}
}

What would be the output if the line


int value = 30;
were changed to
int value = 50;
Object Oriented Programming - CoSc2051 7
When Exception Handling Should Be Used
– When method cannot complete its task.
– Process exceptions from program components.
– Handle exceptions in a uniform manner in large projects.
– Handle Invalid user input.
– When possible Code errors.
– Opening an unavailable file.

Object Oriented Programming - CoSc2051 8


Exception Types
 Exceptions are objects, and objects are defined using classes.
 The root class for exceptions is java.lang.Throwable.
 The Throwable class contains a string that can be used to describe
the exception.
 The Throwable class is the root of exception classes.
 All Java exception classes inherit directly or indirectly from
Throwable.
 You can create your own exception classes by extending Exception
or a subclass of Exception.

Object Oriented Programming - CoSc2051 9


Exception Types
 The exception classes can be classified into three major types:
 system errors,
 exceptions,
 and runtime exceptions.
 System errors are thrown by the JVM and are represented in the
Error class.
 Exceptions are represented in the Exception class, which describes
errors caused by your program and by external circumstances.
 Runtime exceptions are represented in the RuntimeException
class, which describes programming errors, such as bad casting,

Object Oriented Programming - CoSc2051 10


Java Exception Hierarchy

 Exceptions are objects.


 Any class designed for throwable objects must extend the class
Throwable or one of its subclasses.
 The Throwable class contains a string that can be used to describe the
exception.
 Exceptions can be of two types:
– Checked Exceptions: the compiler checks that your methods throw
only the exceptions they have declared themselves to throw.
– Unchecked Exceptions: conditions that reflect errors in your
program's logic and cannot be reasonably recovered from at run time.

Object Oriented Programming - CoSc2051 11


Exception Types
 Exceptions can be of two types:
– Checked Exceptions: the compiler checks that your methods
throw only the exceptions they have declared themselves to throw.
– Unchecked Exceptions: conditions that reflect errors in your
program's logic and cannot be reasonably recovered from at run
time.
 RuntimeException, Error, and their subclasses are known as
unchecked exceptions.
 All other exceptions are known as checked exceptions.
 meaning that the compiler forces the programmer to check and deal
with them in a try-catch block or declare it in the method header

Object Oriented Programming - CoSc2051 12


Exception Types(1) - Checked Exceptions
 All Java exception classes inherit directly or indirectly from Throwable.
 An IOException is also known as a checked exception.
 They are checked by the compiler at the compile-time and the
programmer is prompted to handle these exceptions.
 Some of the examples of checked exceptions are:
 Trying to open a file that doesn’t exist results in
FileNotFoundException
 Trying to read past the end of a file.

Object Oriented Programming - CoSc2051 13


Exception Types(2) - unchecked Exceptions
 Reflect errors in your program's logic.
 A runtime exception happens due to a programming error.
 They are also known as unchecked exceptions.
 These exceptions are not checked at compile-time but at run-time.
 Some of the common runtime exceptions are:
 Improper use of an API - IllegalArgumentException
 Null pointer access (missing the initialization of a variable) -
NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException

Object Oriented Programming - CoSc2051 14


Exception Types(2) - unchecked Exceptions
 You can think about it in this way.
 “If it is a runtime exception, it is your fault”.
 The NullPointerException would not have occurred if
you had checked whether the variable was initialized or not
before using it.
 An ArrayIndexOutOfBoundsException would not have
occurred if you tested the array index against the array
bounds.

Object Oriented Programming - CoSc2051 15


Java Built Exception Classes
 Object is the mother class for all the java classes.
 Exception is the parent class for all the exceptions.
 All exception classes are subtypes of the java.lang.Exception
class.
 The exception class is a subclass of the Throwable class.
 Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
– Errors are not normally trapped form the Java programs.

Object Oriented Programming - CoSc2051 16


Java Built Exception Classes
.
Object
• These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer.
Throwable • Errors are typically ignored in your code because you
can rarely do anything about an error.
Error • For example, if a stack overflow occurs, an error
Exceptions will arise.
• They are also ignored at the time of compilation.
ClassNotFoundException

IOException
Checked Exception
InterruptedException

NumberFormatException

RuntimeException

ArithmeticException

ArrayIndexOutOfBoundsException
Unchecked Exception
NullPointerException

Object Oriented Programming - CoSc2051 17


Java’s Built-in Exceptions(Unchecked
Exception)

 Object is the mother class for all the java classes.


 Exception is the parent class for all the exceptions.
 All exception classes are subtypes of the java.lang.Exception
class.
 The exception class is a subclass of the Throwable class.
 Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
– Errors are not normally trapped form the Java programs.

Object Oriented Programming - CoSc2051 18


Java’s Built-in Exceptions(checked Exception)
 The classes that inherit all the exceptions from the throwable parent
class directly, but except for the run-time exception, are called the
checked exceptions.
 A checked exception extends the Exception class.

Object Oriented Programming - CoSc2051 19


Checked vs Unchecked Exception
Checked Exception Unchecked Exception
 Can be checked and handled  Cannot be checked nor be handled
. during Compile-time during Compile-time
 Direct subclasses of exception  Direct subclasses of exception class
class but do not inherit run-time but only inherits run-time exception
exception
 The compiler catches these  The compiler cannot recognize and
exceptions in the compilation catch them during the compilation
stage stage
 Checked Exceptions are  Uncheck exceptions are unpredictable
predictable failures failures, mostly caused by improper
programming logic
 Examples:  Examples:
 SQL Exception  ArithmeticException
 IOException  NullPointerException

Object Oriented Programming - CoSc2051 20


Exceptions Methods

Object Oriented Programming - CoSc2051 21


How to handle exceptions?
 In Java, exception handling proceeds as follows:
 Either some library software or your code provides a
mechanism that signals when something unusual happens.
 This is called throwing an exception.
 At another place in your program you put the code that deals
with the exceptional case.
 This is called handling the exception.
 Here's a list of different approaches to handle exceptions in Java.
 try...catch block
 finally block
 throw and throws keyword
Object Oriented Programming - CoSc2051 22
try block….
 It “tries” to execute the case where all goes smoothly.
 If something exceptional does happen, you want to throw an
exception.
 Indicates that something unusual happened.
 The basic outline, when we add a throw, is as follows:

try {
// code
} catch(Exception e) {
// code
}

Object Oriented Programming - CoSc2051 23


try block….
Try. … Catch Exception Example
public class TryCatchException {

public static void main(String[] args) {


try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}

Object Oriented Programming - CoSc2051 24


catch block
 A catch block begins execution when an exception is thrown in the
try block.
 The catch block has a parameter.
 Exception object thrown is plugged in for this catch block parameter.
 Executing of the catch block is called catching the exception or
handling the exception.
 When an exception is thrown, it should ultimately be handled by
(caught by) some catch block.
 Catch block immediately follows the try block.
 The catch block catches the exception and statements inside the
catch block is executed.
Object Oriented Programming - CoSc2051 25
catch block
 When an exception is thrown, it can be caught and handled in a try-
catch block, as follows:

try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
...
catch (ExceptionN exVarN) {
handler for exceptionN;
}

 If no exceptions arise during the execution of the try block, the


catch blocks are skipped.

Object Oriented Programming - CoSc2051 26


Example 1
class Division {
public static void main(String[] args {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}

Object Oriented Programming - CoSc2051 27


Example 2
class Exceptions {
public static void main(String[] args) {
String languages[] = { "C", "C++", "Java", "Perl",
"Python" };
Output of the program.
try {
C++
for (int c = 1; c <= 5; c++) {
Java
System.out.println(languages[c]); Perl
}// end of for loop Python

}
java.lang.ArrayIndexOutOfBoundsE
catch (Exception e) { xception: 5
System.out.println(e);
}
}
}

Object Oriented Programming - CoSc2051 28


Java throw and throws keyword
Java throw
 The Java throw keyword is used to explicitly throw a single
exception.
 When we throw an exception, the flow of the program moves from
the try block to the catch block.
 The “throw” keyword throws an exception.
public class ThrowException {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Object Oriented Programming - CoSc2051 29
Declaring exceptions
Java throws
 Similarly, the throws keyword is used to declare the type of exceptions
that might occur within the method.
 The “throws” keyword is used to declare an exception. Its syntax is:

accessModifier returnType methodName() throws


ExceptionType1, ExceptionType2 … {
// code
}
 Including an exception class in a throws clause is called declaring the
exception. Example
 public void sampleMethod() throws DivisionByZeroException

Object Oriented Programming - CoSc2051 30


Declaring exceptions…
throws Example

public class ThrowsException {

public static void findFile() throws IOException {


// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}

public static void main(String[] args) {


try {
findFile(); java.io.FileNotFoundException
} catch (IOException e) { : test.txt (No such file or
}
System.out.println(e);
directory)
}
}

Object Oriented Programming - CoSc2051 31


Declaring exceptions…
Recap throws Example
 When we run this program, if the file test.txt does not exist,
FileInputStream throws a FileNotFoundException which extends the
IOException class.
 If a method does not handle exceptions, the type of exceptions that
may occur within it must be specified in the throws clause so that
methods further up in the call stack can handle them or specify them
using throws keyword themselves.
 The findFile() method specifies that an IOException can be thrown.
 The main() method calls this method and handles the exception if
it is thrown.
Object Oriented Programming - CoSc2051 32
Declaring exceptions…
• If there is more than one possible exception that can be thrown in the
method definition, then the exception types are separated by commas.
public void sampleMethod() throws DivisionByZeroException,
SomeOtherException
– This technique is a form of shifting responsibility (“passing the buck”).
• If you define a method that might throw exceptions of some particular
class, then normally either
– Your method definition must include a catch block that will catch
the exception or
– You must declare (that is, list) the exception class within a throws
clause.

Object Oriented Programming - CoSc2051 33


Declaring exceptions…
 To declare an exception in a method, use the throws keyword in the
method header, as in this example:

public void myMethod() throws IOException


 The throws keyword indicates that myMethod might throw an
IOException.
 If the method might throw multiple exceptions, add a list of the
exceptions, separated by commas, after throws:
public void myMethod()
throws Exception1, Exception2, ..., ExceptionN

Object Oriented Programming - CoSc2051 34


Catch or Declare Rule
• Most “ordinary” exceptions that might be thrown when a method is
invoked must be accounted for in one of two ways:
– The possible exception can be caught in a catch block within the
method definition.
– The possible exception can be declared at the start of the method
definition by placing the exception class name in a throws clause.
• This is known as the Catch or Declare Rule.
• In any one method, you can mix the two, catching some exceptions
and declaring others in a throws clause.

Object Oriented Programming - CoSc2051 35


The finally Block
• The finally block contains code to be executed whether or not an
exception is thrown in a try block.
• The finally block, if used, is placed after a try block and its following
catch blocks.
• The general syntax is as follows:
try {
//some code here
}catch(Exception e){
System.out.println("Trying to divide by 0 "+ e);
}
finally{
System.out.println("Don't worry I always excuted ");
}
}
}
Object Oriented Programming - CoSc2051 36
The finally Block
• There is 3 possibilities when the code in the try-catch-finally
blocks is run:
1. The try block runs to the end and no exception is thrown.
• In this case, the finally block is executed after the try block.
2. An exception is thrown in the try block and is caught in one of
the catch blocks positioned after the try block.
• In this case, the finally block is executed after the catch block is
executed.
3. An exception is thrown in the try block and there is no matching
catch block in the method to catch the exception.
• In this case, the method invocation ends and the exception object is
thrown to the enclosing method. However, the finally block is
executed before the method ends.
Object Oriented Programming - CoSc2051 37
The finally Block Example
class Allocate {
public static void main(String[] args){
. try {
long data[] = new long[1000000000];
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("finally block will execute always.");
}
}
}

Output of program:
finally block will execute always.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap
space at Allocate.main(Allocate.java:5)

Object Oriented Programming - CoSc2051 38


Bye

Take a look : https://docs.oracle.com/en/java/

Object Oriented Programming - CoSc2051 39

You might also like