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

Presentation 7

The document discusses exception handling in Java, explaining the concept of exceptions and how to manage them using try-catch blocks. It covers various types of exceptions, including checked and unchecked exceptions, and emphasizes the advantages of using exception handling to separate error management from regular code. Additionally, it highlights the importance of grouping exceptions and the proper use of multiple catch blocks in handling different exception types.

Uploaded by

kakefon876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Presentation 7

The document discusses exception handling in Java, explaining the concept of exceptions and how to manage them using try-catch blocks. It covers various types of exceptions, including checked and unchecked exceptions, and emphasizes the advantages of using exception handling to separate error management from regular code. Additionally, it highlights the importance of grouping exceptions and the proper use of multiple catch blocks in handling different exception types.

Uploaded by

kakefon876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

IT 214

Object
Oriented
Programming
Dr. Abdulaziz Saleh Algablan
Email: [email protected]
2023
Topics

Exception Handling
What is the Problem ?
a) public static int divide( int a, int b )
{
try{
return a / b;
}
catch() {}
}
b) public static void getUserInput()
{
// declaration of scanner.
// some code
int age = scanner.nextInt();
scanner.next();
}
What is the Problem ?
• For (a), if the following is entered:
• a = 100
• b =0
• Exception in thread "main" java.lang.ArithmeticException: / by zero

• For (b), assume the user entered “I am happy”.


• Exception in thread "main" …..
Exception
• An exception is an indication of a problem that occurs during a
program’s execution.
• Exception handling enables you to create applications that can resolve
(or handle) exceptions.
• In many cases, handling an exception allows a program to continue
executing as if a problem had been encountered.
• if there is no exception code and there is an error, the program will terminate.
• When an exception occurs, the normal sequence of flow is
terminated, and the exception-handling routine is executed.
Try … catch()
• Java try block is used to enclose the code that might throw an
exception.
• try-catch must be used within the method.
• The try-catch statement is comprised of a try block and either a catch
block, a finally block, or both.
• The code in the try block is executed first, and if it throws an
exception, the code in the catch block will be executed.
The code in the finally block will always be executed before
control flow exits the entire construct.
Try … catch()
• A try block inside another try block is called a nested try block.
• We need such structures in few situations when a piece of code
contained in a try code may be such that some lines raise certain
exceptions and another piece of code raises a completely different
exception.
Catching Exceptions
• A catch block begins with the keyword catch and is followed by a
parameter in parentheses (called the exception parameter) and a
block of code enclosed in curly braces.
• Exception class is the parent class of all exception in Java.
• Each catch block can have only a single parameter
• specifying a comma-separated list of exception parameters is a syntax error.
Try-catch in Use

public static void getUserInput()


{
// declaration of scanner.
// some code
try {
int age = scanner.nextInt();
scanner.next();
}
catch (InputMismatchException e) {
System.out.println(“Please enter a number”);
getUserInput();
}
}
Throw Exception
• An exception can be thrown using the throw statement.
• Its syntax is
• throw new <a throwable object>;
Exception Types
• Java defines several types of exceptions that relate to its various class
libraries.
• Java also allows users to define their own exceptions.
User-defined Exception
public static void getUserInput() throws
AgeException class AgeException extends Exception{ }
{
try {
int age = scanner.nextInt();
scanner.next();
if(age > 150)
throw new AgeException();
}
catch (AgeException e) {
System.out.println(“Please enter a number”);
getUserInput();
}
catch (InputMismatchException e) {
System.out.println(“Please enter a number”);
getUserInput();
}
}
Exception Class
package java.lang;
public class Exception extends Throwable {
@java.io.Serial
static final long serialVersionUID = -3387516993124229948L;
public Exception() {
super();}
public Exception(String message) {
super(message);}
public Exception(String message, Throwable cause) {
super(message, cause)}
public Exception(Throwable cause) {
super(cause);}
protected Exception(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);}}
Built-in Exception
• Checked Exception
• known as compile-time exceptions as these exceptions are checked by the
compiler.
• The exception must be handled by the programmer.
• If not, then the system displays a compilation error.
• Examples: SQLException, IOException, InvocationTargetException, and ClassNotF
oundException.
• Unchecked Exception
• Exceptions that occur during the execution of the program.
• These exceptions are generally ignored during the compilation process.
• They are not checked while compiling the program.
• For example, programming bugs like logical errors, and using incorrect APIs.
Built-in Exception
• Checked exception
• The compiler does not allow the yellow code without try-catch
import java.io.FileInputStream;
//.. Class definition
// … Some code
public static void main(String[] args) {
FileInputStream input1 = null;
input1 = new FileInputStream("C:/file.txt");
}
Advantages of Exception Handling
• By using exceptions to manage errors, Java programs have some
advantages over traditional error management techniques.
• Advantage 1: Separating Error Handling Code from "Regular" Code.
• Advantage 2: Propagating Errors Up the Call Stack.
• Advantage 3: Grouping & Ordering Error Types.
Separating Error Handling Code
from "Regular" Code
void readFile(…) {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
catch (fileOpenFailed) { doSomething; }
catch (sizeDeterminationFailed) { doSomething; }
catch (memoryAllocationFailed) { doSomething; }
catch (readFailed) { doSomething; }
catch (fileCloseFailed) { doSomething; }
}
Without Try-catch
void readFile(…) {

open the file;


IF (fileOpenFailed) { doSomething; }
determine its size;
open another file;
IF (fileOpenFailed) { doSomething; }
IF (sizeDeterminationFailed) { doSomething; }
allocate that much memory;
IF (memoryAllocationFailed) { doSomething; }
read the file into memory;
IF (readFailed) { doSomething; }
close the file;
IF (fileCloseFailed) { doSomething; }
}
Propagating Errors Up the Call
Stack
• with throws keyword after method signature, we can make the
caller method deals with errors (in single place).
• Example:
void method1 {
try { call method2; }
catch (exception) { do Error
Processing; }
}
void method2(…) throws exception
{ call method3; }
void method3(…) throws exception
{ call readFile; }
Propagating Errors Up the Call
Stack
• When an error happens in readfile, method3, or method 2, there is
one place to handles the error.
• The error handling occurs in method1.

• What if Java does not have try-catch exception handling ?


Propagating Errors Up the Call
Stack
method1 {
ErrorCodeType error; class ErrorCodeType
error = call method2; {
if (error != null )
doErrorProcessing; String errorMessage;
else String lineOfError;
proceed;
} …
ErrorCodeType method2 {
ErrorCodeType error = null;
error = call method3; }
if (error) return new ErrorCodeType();
else proceed; return null;
}
ErrorCodeType method3 {
ErrorCodeType error = null;
error = call readFile;
if (error) return new ErrorCodeType();
else proceed; return null;}
Grouping of Error Types
• Exceptions fall into categories or groups.
• All exceptions that are thrown within a Java program are first-class
objects.
• Grouping or categorization of exceptions is a natural outcome of the
class hierarchy.
• When there are multiple catch blocks in a try-catch statement, they
are checked in sequence.
• Because the exception classes form an inheritance hierarchy, it is
important to check the more specialized exception classes before the
more general exception classes.
Multiple Catch Blocks
try { ...
} catch (Exception e) { ...
} catch (InputMismatchException e) { ...
}
• The second catch block will never be executed because any exception
object that is an instance of Exception or its subclasses will match the
first catch block.
• When an exception is thrown, a matching catch block is executed and
all other catch blocks are ignored.
The end.

You might also like