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

Chapter Five Exception Handling 2023

The document discusses exception handling in Java, including an overview of exceptions, the Java exception hierarchy with checked and unchecked exceptions, how to handle exceptions using try, catch, throw, throws and finally keywords, and how to define custom user exceptions by extending the Exception class. It provides examples of exception handling code and discusses when to use exception handling to maintain normal program flow.

Uploaded by

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

Chapter Five Exception Handling 2023

The document discusses exception handling in Java, including an overview of exceptions, the Java exception hierarchy with checked and unchecked exceptions, how to handle exceptions using try, catch, throw, throws and finally keywords, and how to define custom user exceptions by extending the Exception class. It provides examples of exception handling code and discusses when to use exception handling to maintain normal program flow.

Uploaded by

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

Chapter 5: Exception Handling

Contents

 Exception handling overview


 Causes of exception and types
 Java exception hierarchy
 Handling exception
 The finally clause
 User defined exception
Overview of exception
 An exception is an unexpected event that occurs during program
execution

 It affects the flow of the program execution which can cause the
program to terminate abnormally.

 An exception is an indication of a problem that occurs during a


program’s execution.
Exception Handling
 In many cases, handling an exception allows a program to continue
execution as if no problem had been encountered.

Exception handling: is a mechanism to handle runtime errors (which allows


exceptions to be thrown and caught)

 Exception handling enables you to create applications that can resolve (or
handle) exceptions.
Advantages of Exception Handling
The core advantage of exception handling is to maintain the normal
flow of the application.
– An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions

The ability to keep cleanup code in a dedicated location and making


sure this cleanup code will execute

The ability to locate and fix bugs in the code


Causes of Exception
 When a program violates the semantic constraints of the java
programming language, the JVM signals the error as an exception
– e.g. index out of bound, division by zero
 A throw statement is executed
– Throw statement is used to explicitly raise an exception
Types of Exception
 Checked Exception
– Are exceptions that are checked at compile time
– The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions
• For example, IOException, SQLException, FileNotFoundException etc.

– If these exceptions are not handled/declared in the program, you will get
compilation error
import java.io.*;
public class Main {

public static void main(String[] args) {


FileInputStream GFG
= new FileInputStream("/Desktop/GFG.txt");
}
}
Cont...
 Unchecked Exception
– The classes that inherit the RuntimeException are known as unchecked
exceptions
• For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
– These exceptions are not checked at compile-time. So, compiler does not
check whether the programmer has handled them or not but it’s the
responsibility of the programmer to handle these exceptions and provide a
safe exit.
– Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Error vs Exception
Error: An Error indicates serious problem that a reasonable
application should not try to catch
– e.g. out of memory error

Exception: Exception indicates conditions that a reasonable


application might try to catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable
(java.lang.Throwable), which is base class of hierarchy.
One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch.
– NullPointerException is an example of such an exception.
Another branch,Error are used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
– StackOverflowError is an example of such an error.
Cont...
Handling Exception
 Customized Exception Handling : Java exception handling is
managed via five keywords:
– try
– catch
– throw
– throws and
– finally
Java Exception keywords
 Try
– The "try" keyword is used to specify a block where we should place an
exception code.
– It means we can't use try block alone. The try block must be followed by
either catch or finally.
 catch
– The "catch" block is used to handle the exception.
– It must be preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
Cont...
Finally
– The "finally" block is used to execute the necessary code of the program. It
is executed whether an exception is handled or not.
 Throw
– The "throw" keyword is used to throw an exception.
 Throws
– The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in a method. It doesn't throw an exception. It is
always used with method signature.
Example
try {
// code that requires common cleanup or
// exception-recovery operations
}
catch (InvalidOperationException) {
//code that recovers from an InvalidOperationException
// (or any exception type derived from it)
}
catch (SomeOtherException) {
// code that recovers from an SomeOtherException
// (or any exception type derived from it)
}
catch {
// code that recovers from any kind of exception
// when you catch any exception, you usually re-throw
throw;
}
finally {
// code that cleans up any operations started
// within the try block. This code ALWAYS executes.
}
User Defined Exception
 In Java, we can create our own exceptions that are derived classes of
the Exception class.
– Creating our own Exception is known as custom exception or user-defined
exception.

Basically, Java custom exceptions are used to customize the exception


according to user need.
Cont...
Why use customer exceptions?
– To catch and provide specific treatment to a subset of existing Java
exceptions
– Business logic exceptions: These are the exceptions related to business logic
and workflow. It is useful for the application users or the developers to
understand the exact problem

 In order to create custom exception, we need to extend Exception class


that belongs to java.lang package.
Example
Class InvalidAgeException extends Exception {
public InvalidAgeException(string str) {
super(str);
}
}

throw new InvalidAgeException(‘Age is not valid to vote’);


Exercise 1
• This program is throwing exception IndexOutOfRangeException. How
do you handle it?
Exercise 2
• Is the following code legal?

You might also like