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

Chapter 5

Chapter 5 discusses exception handling in Java, explaining that exceptions are problems that occur during program execution, interrupting the normal flow. It covers the types of exceptions, including checked and unchecked exceptions, and the keywords used for exception handling: try, catch, throw, throws, and finally. The chapter emphasizes the importance of handling exceptions to create robust applications and provides examples of how to implement exception handling in Java code.

Uploaded by

Daniel Amare
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)
4 views

Chapter 5

Chapter 5 discusses exception handling in Java, explaining that exceptions are problems that occur during program execution, interrupting the normal flow. It covers the types of exceptions, including checked and unchecked exceptions, and the keywords used for exception handling: try, catch, throw, throws, and finally. The chapter emphasizes the importance of handling exceptions to create robust applications and provides examples of how to implement exception handling in Java code.

Uploaded by

Daniel Amare
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

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

 When an Exception occurs we get a System generated error message.

 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?

 Wrong data entered by the user

 The file we want to load may be missing or in the wrong format.

 Trying to access an out - of –bounds array elements.

 Exception handling enables us to create applications that can resolve exceptions.

 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.

Here is the overview

 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.

 throw: To manually throw an exception, use the keyword throw.

 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.

► It is followed by one or more catch blocks or a finally block.

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.

► Multiple catch blocks can be used to handle different types of exceptions.

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.

 The Throwable class has two subclasses


Error and Exception.

 Error and Exception classes are used for


handling errors in java.

11
Checked Vs unchecked exception

 In Java, there are two types of exceptions: checked & unchecked.

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.

► It is up to the programmers to be civilized, and specify or catch the exceptions.


12
Java’s Built-in Exceptions
 ArrayStoreException Assignment to an array
 Inside the standard package java.lang, Java defines
element of an incompatible type.
several exception classes.
 ClassCastException Invalid cast.
 The most general of these exceptions, are subclasses of
 IllegalArgumentException Illegal argument used to
the standard type RuntimeException.
invoke a method.
 Since java.lang is implicitly, imported into all Java  IllegalMonitorStateException Illegal monitor
programs, most exceptions derived from operation, such as waiting on an unlocked thread.
RuntimeException are automatically available.  IllegalStateException Environment or application is

 ArithmeticException Arithmetic error, such as divide- in incorrect state.

by-zero.  IllegalThreadStateException Requested operation


not compatible with current thread state.
 ArrayIndexOutOfBoundsException Array index is
 IndexOutOfBoundsException Some type of index
out-of-bounds.
is out-of-bounds.
13
Uncaught exception

 Example  Try catch Example

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 {

System.out.println("inside procA"); } finally { System.out.println("procC's finally"); }


throw new RuntimeException("demo"); }
} finally {
public static void main(String args[]) {
System.out.println("procA's finally");}

} try {
static void procB() { procA();
try {
} catch (Exception e) {
System.out.println("inside procB");

} finally { System.out.println("procB's finally"); }


System.out.println("Exception caught");
} }
static void procC() {
procB();

procC();

}
}.

18

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