Chapter 5
Chapter 5
Exception handling
1
Exception handling
An exception is an indication of problem that happens during a program's execution .
Exception is any abnormal, unwanted evets or some extraordinary conditions that occur at
runtime.
It interrupts the normal flow of the program as the exception terminates program execution
In Java, exceptions are represented by classes that inherit from the java.lang.Exception class.
When an exceptional situation occurs, such as division by zero, array index out of bounds, or
file not found, an exception object is created and thrown.
2
Exception handling
Why exception occurs?
Exception handling enable programmers to write robust and fault tolerant application that can notify the
users before they terminate the program.
A java program with exception handling notify the user about the mistake happens with the input.
3
Error & Exception handling
Error occurred in a program can be of two types: syntax error and runtime error.
Syntax errors are also known as compile time error which mainly occurs during the compilation of
a program.
These errors arise mainly due to improper syntax in our program like missing semi colon,
misbalanced parenthesis, wrongly spelled keywords, illegal identifiers etc.
When a syntax error occurs the compiler shows us an error message specifically to line where the
error occurs, it may show red line but it depends on the programming language.
To fix such errors in our program we need to review our code and correct they syntax depending
on the rule of the programming language we are using.
4
Runtime Errors
As the name indicates they occur at runtime rather than in compilation phase.
The reason behind those errors may be trail of a program to so something which is out of the rule
or trying to access the locked resource without having privilege.
These errors are mainly detected by the JVM while executing the program.
Logic errors: These errors occur when the program doesn't work as intended, even though it may
be free of syntax and runtime errors. It's like writing a sentence that provides the wrong meaning.
Logic errors are harder to detect because they don't produce error messages or crash the program.
The programmer may to review his code in detail to detect such errors that causes to produce
incorrect result .
5
Error & Exception handling overview
Exception Handling enables programmers to handle and recover a program from a runtime
errors or exceptional situations that may occur during the execution of the program.
Exception handling enables us to create applications that can resolve (handle) exceptions.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
6
Cont’d …
try block: The statements which are expected to throw exception are kept inside try block.
catch block: If an exception occurs within the try block, it throws an exception to the
catch block which handle it in some rational manner.
throws: A throws clause lists the types of exceptions that a method might throw.
Finally: Any code that absolutely must be executed before a method returns is put in a
finally block
7
Cont’d …
try block
► This block encloses the code that may potentially throw an exception.
catch
► This block is used to catch and handle specific exceptions that occur within the
corresponding try block.
► It specifies the type of exception to catch and provides code to handle the exception.
8
Cont’d …
finally
► This block is optional and is used to specify code that should be executed regardless of
whether an exception occurs or not. It is often used to release resources or perform cleanup
operations.
► When an exception is thrown, the Java runtime system searches for a suitable catch block
that can handle the exception based on the type of exception thrown.
► If a matching catch block is found, the corresponding code is executed. If no suitable catch
block is found, the exception is propagated up the call stack until it is caught or the
program terminates.
9
Continued…
General form of Exception handling block
Execution Flow of the try, try{
catch and finally block // block of code will be here
Try Block
}
Catch(ExceptionType1 exob)
{
Catch Block //exception handler for exception type1
}
finally finally{// code to be executed before try
finally
block ends
}
10
Exception types
Error and exception
All exception types are subclasses of
the built-in class Throwable. Thus,
Throwable is at the top of the exception
class hierarchy.
11
Checked Vs unchecked exception
Checked Exception
They are checked at compile time. If some code within a method throws a checked exception,
then the method must either handle the exception or it must specify the exception using throws
keyword.
Unchecked Exception
► They are exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the exception.
14
Continued…
Multiple catch blocks
In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, you can specify two or more catch clauses, each catching
a different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues
after the try/catch block. The following example traps two different exception types:.
15
Exception
Example Try catch Example
do {
try {
An InputMismatchException occurs when Scanner method NextInt System.out.println("Please Enter 1st
receives a string that doesn’t represent a valid integer integer:");
int num=input.nextInt();
System.out.println("Please Enter 2nd
package exceptionHandling; integer:");
import java.util.InputMismatchException; int den=input.nextInt();
import java.util.Scanner; int quetient=Quetient(num,den);
import java.util.Scanner.*; System.out.println("the result
is:"+quetient);
Loop=false;
public class ExceptionHandlingInput { }
public static int Quetient(int Num,int Den) catch (ArithmeticException e) {
throws ArithmeticException System.out.println("Please input valid
{ Denominator !=0 ");
return Num/Den; }
} catch(InputMismatchException exc) {
input.nextLine();
System.out.println("pleaseInput Integer only
not character!!");
}}
while(Loop);
}}
16
Finally…
finally creates a block of code that will be executed after a try /catch block has completed and
before the code following the try/catch block finally block will execute whether or not an
exception is thrown
If an exception is thrown, the finally block will execute even if no catch statement matches the
exception useful for closing file handles and freeing up any other Resources finally clause is
optional.
17
Finally…
class FinallyDemo {
try {
static void procA() {
System.out.println("inside procC");
try {
} try {
static void procB() { procA();
try {
} catch (Exception e) {
System.out.println("inside procB");
procC();
}
}.
18