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

OOP Chapter IV

The document provides an overview of exception handling in Java, explaining its purpose, types of exceptions, and how to manage them using try-catch blocks. It details the difference between checked and unchecked exceptions, and introduces the finally block, which executes regardless of whether an exception occurs. The document includes examples to illustrate exception handling concepts and their implementation in Java programming.

Uploaded by

mersimoybekele88
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)
3 views

OOP Chapter IV

The document provides an overview of exception handling in Java, explaining its purpose, types of exceptions, and how to manage them using try-catch blocks. It details the difference between checked and unchecked exceptions, and introduces the finally block, which executes regardless of whether an exception occurs. The document includes examples to illustrate exception handling concepts and their implementation in Java programming.

Uploaded by

mersimoybekele88
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/ 18

Wolaita Sodo University

School of Informatics
Department of Computer Science

Object Oriented Programming (CoSc2051)

Compiled by Dawit Uta. (M. Tech.)


Computer Science Department, WSU
website address: www.davidtechnotips.com
2 Course outline: Chapter 4 Exception Handling

 Exceptions Overview

 Catching Exceptions

 Exception Methods

 Declaring Exceptions

 Defining and Throwing Exceptions

 Errors and Runtime Exceptions


3 Exception handling overview
 What is an Exception? is a problem that arises during the execution of a program that
disrupts the program flow and may cause a program to fail or terminates abnormally, which
is not recommended, therefore, these exceptions are to be handled.
 Some examples are:.
 Accessing an out-of-bounds array element

 Performing illegal arithmetic

 Illegal arguments to methods

 Hardware failures

 Writing to a read-only file


4

 Exception handling: is one of the powerful mechanism to handle the runtime


errors so that the normal flow of the application can be maintained.
 It is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
 Exception handling enables you to create applications that can resolve (or
handle) exceptions.
 It help you write robust and fault-tolerant programs that can deal with
problems and continue executing or terminate gracefully.
 only classes that extend Throwable (package java.lang) directly or indirectly
can be used with exception handling.
5

 This enables you to add application-specific information to the original


exception.
 exception-handling features that were introduced in Java SE 7 catching
multiple exceptions with one catch handler and the new try-with-resources
statement that automatically releases a resource after it’s used in the try block.
 The core advantage of exception handling is to maintain the normal flow of
the application.
 In the next slide you will se the program that throws exception due to invalid
division, which crashes the flow of the program.
6
7
Hierarchy of Java Exception classes
8
The java.lang.Throwable class
is the root class of Java
Exception hierarchy inherited
by two subclasses: Exception
and Error.
9

There are mainly two types of exceptions:


checked and unchecked. An error is
considered as the unchecked exception.
However, according to Oracle, there are
three types of exceptions namely:
10 Exception terminologies
 When an exception happens we say it was thrown or raised

 When an exception is dealt with, we say the exception was handled or caught

 Unchecked Exceptions: 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 numerous and ignored at the time of compilation.

 Checked Exceptions: 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.

 Example reading data from a non existing file.


11
Exception handling overview
For example, if you have declared an array of size 2 in your program, and trying to call the 3rd
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class ExceptionExample {


public static void main(String
args[]) {
String[] greek = {"Alpha",
"Beta"};
System.out.println(greek[2]);
}
}
 Exception in thread "main"
 java.lang.ArrayIndexOutOfBoundsException: 2
 at ExceptionExample.main(ExceptionExample.java:4)
Exception handling overview
12

Exception Message Details


Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
 What exception class? ArrayIndexOutOfBoundsException
 Which array index is out of bounds? 2
 What method throws the exception? main
 What file contains the method? ExceptionExample.java
 What line of the file throws the exception? 4
13 Exception Handling
Use a try-catch block to handle exceptions that are thrown

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
public class JavaExceptionExample{
public static void main(String args[]){
14
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Exception in thread main


java.lang.ArithmeticException:/ by zero
rest of the code...
15 Example
The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which
throws an exception.
Finally block
16

 Programs that obtain certain resources must return them to the system to
avoid so-called resource leaks.
 In programming languages such as C and C++, the most common resource
leak is a memory leak.
 Java performs automatic garbage collection of memory no longer used
by programs, thus avoiding most memory leaks.
 However, other types of resource leaks can occur.
 For example, files, database connections and network connections that are
not closed properly after they’re no longer needed might not be available for
use in other programs.
Finally block
17

 In Java, the finally block is always executed no matter whether there is


an exception or not.
If an exception occurs, the finally block is
try { //code executed after the try...catch block. Otherwise,
} catch (ExceptionType1 e1) { it is executed after the try block. For each try
block, there can be only one finally block.
// catch block
The one case in which the finally block will
} not execute is if the application exits early
finally { from a try block by calling method System.exit
// finally block always executes } If an exception that occurs in a try block
cannot be caught by one of that try block’s
Example: Next slide shows catch handlers, the program skips the rest of
exception handling using finally the try block and control proceeds to the
block finally block.
class trycatchfinalExample{
18 public static void main(String[] args) {
try { // code that generates exception
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {

The End of chapter four


System.out.println("ArithmeticException => " + e.getMessage()); }
finally {
System.out.println("This is the finally block");
}
}
Output }
ArithmeticException => / by zero
This is the finally block
In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an ArithmeticException.
The exception is caught by the catch block. And, then the finally block is executed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy