You are on page 1of 24

Chapter 4

Exception
Handling

1 By Abdu A; 10/7/22
Exception
 An exception is a problem that arises during the execution of a
program. Or An exception is an event, which occurs during the
execution of the program, that interrupt the normal flow of the
program‘s instruction. An exception can occur for many different
reasons, including the following:
o A user has entered invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of
communications.
 Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have
failed in some manner.
2 By Abdu A; 10/7/22
Exception Types
1. Checked exceptions: A checked exception is an exception
that is typically a user error or a problem that cannot be
foreseen by the programmer.
 The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
For example: IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

3 By Abdu A; 10/7/22
Exception Types
2. Runtime exceptions: A runtime exception is an exception that
occurs that probably could have been avoided by the programmer. As
opposed to checked exceptions, runtime exceptions are ignored at the
time of compilation.
 The classes that inherit the RuntimeException are known as
unchecked exceptions. For example: ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
 Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
3. Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are typically
ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
4 By Abdu A; 10/7/22
Exception Types
 The Throwable class is the root of exception classes.
 All Java exception classes inherit directly or indirectly
from Throwable.
 You can create your own exception classes by extending
Exception or a subclass of Exception.
 The exception classes can be classified into three major
types:
 system errors,
 exceptions, and
 runtime exceptions.

5 By Abdu A; 10/7/22
System errors
 System errors are thrown by the JVM and are represented
in the Error class.
 The Error class describes internal system errors, though
such errors rarely occur.
 If one does, there is little you can do beyond notifying the
user and trying to terminate the program gracefully.
 Examples of Subclasses of Error

6 By Abdu A; 10/7/22
Exceptions
 Exceptions are represented in the Exception class,
which describes errors caused by your program and
by external circumstances.
 These errors can be caught and handled by your
program.
 Examples of Subclasses of Exception

7 By Abdu A; 10/7/22
Runtime exceptions
 Runtime exceptions are represented in the
RuntimeException class, which describes
programming errors, such as bad casting, accessing an
out-of-bounds array, and numeric errors.
 Runtime exceptions are generally thrown by the JVM.
 Examples of Subclasses of RuntimeException

8 By Abdu A; 10/7/22
Compile time exception vs. Run time exception
1 Compile time exception
Compiler time error means Java compiler identify the syntax
error at the time of compilation. And without successfully
compilation, compiler does not create .class file. That means we
have to compile the program which should be error free and then
compiler creates .class file of the program and then we can run
the program.
The common problems are:
 Missing braces
 Missing semicolon
 Missing double quote in string
 = instead of == operator And so on.

9 By Abdu A; 10/7/22
 
For example:
class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b
System.out.println("Division is” +c);
}
}

10 By Abdu A; 10/7/22
2. Run time exception
 Several time program may compile successfully and
compiler creates the .class file of the program but when
the time of running the program, it shows the error and
that type of error called run time error.
 The common problems are:
 Divide by zero
 Conversion of invalid string to number
 access the element that is out of bound of an array
 Passing the parameters with invalid range. And so on.

11 By Abdu A; 10/7/22
For example: write a program to find out
division of two numbers.

class Try1 Output:


{
public static void main(String
args[]) Exception in thread "main"
{ java.lang.ArithmeticExcept
int a=12; ion: / by zero
int b=0; at Try1.main(Try1.java:7)
int c=a/b;  
System.out.println("Division
is"+c);
}
}
12 By Abdu A; 10/7/22
Exception Hierarchy
 Exceptions are objects, and objects are defined using classes.
 The root class for exceptions is java.lang.Throwable.

13 By Abdu A; 10/7/22
Catching Exceptions
 To handle an exception in a program, the line that throws the exception is executed
within a try block. A try block is followed by one or more catch clauses.
 A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within
a try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following:
try
{
//Protected code
}catch(Exception Name e1)
{
//Catch block
}
 A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked.
14 By Abdu A;
10/7/22
Example1 of try/catch
public class demo { 
public static void main(String[] args) {  

Output: 
int ans1, ans2; 
int a = 2, b = 2, c = 0; 
try  {
 ans1 = a/b;
System.out.println("a/b = " + ans1);

 a/b = 1
ans2 = a/c; 
System.out.println("a/c = " + ans2); 

catch(Arithmetic Exception e)

 Arithmetic
Exception!
System.out.println("Arithmetic Exception!"); 
}
System.out.println("demo is over");

}
demo is over 
   
15 By Abdu A; 10/7/22
Throws/Throw
 If a method does not handle a checked exception,
the method must declare it using the throws
keyword.
 The throws keyword appears at the end of a
method's signature.
 You can throw an exception, either a newly
instantiated one or an exception that you just caught,
by using the throw keyword.

16 By Abdu A; 10/7/22
Remote Exception

public class className


{
public void deposit(double amount) throws Remote Exception
{
// Method implementation
throw new Remote Exception();
}
//Remainder of class definition
}

17 By Abdu A; 10/7/22
Example:
Function throws a RemoteException and an InsufficientFundsException

public class className


{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

18 By Abdu A; 10/7/22
Finally Keyword
 The finally keyword is used to create a
block of code that follows a try block.
A finally block of code always executes,
whether or not an exception has occurred.
 Using a finally block allows you to run any
cleanup-type statements that you want to
execute, no matter what happens in the
protected code.

19 By Abdu A; 10/7/22
Con`t

Note the followings:


 A catch clause cannot exist without a try
statement.
 It is not compulsory to have finally clauses
when ever a try/catch block is present.
 The try block cannot be present without either
catch clause or finally clause.

20 By Abdu A; 10/7/22
Syntax:
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
finally
{
//The finally block always executes.
}

21 By Abdu A; 10/7/22
Example:
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]);
}
catch(Array IndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

22 By Abdu A; 10/7/22
Errors and Runtime Exceptions
 RuntimeException, Error, and their subclasses
are known as unchecked exceptions.
 All other exceptions are known as checked
exceptions, meaning that the compiler forces
the programmer to check and deal with them in
a try-catch block or declare it in the method
header.

23 By Abdu A; 10/7/22
24 By Abdu A; 10/7/22

You might also like