0% found this document useful (0 votes)
11 views51 pages

OOP Chapter 4

Chapter 4 discusses exception handling in Java, explaining the nature of exceptions, how to catch and throw them, and the importance of handling exceptions to maintain program stability. It covers various types of exceptions, including built-in, checked, and unchecked exceptions, along with examples demonstrating proper exception handling techniques. The chapter emphasizes the use of keywords like try, catch, finally, throw, and throws in managing exceptions effectively.

Uploaded by

babsobatu
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)
11 views51 pages

OOP Chapter 4

Chapter 4 discusses exception handling in Java, explaining the nature of exceptions, how to catch and throw them, and the importance of handling exceptions to maintain program stability. It covers various types of exceptions, including built-in, checked, and unchecked exceptions, along with examples demonstrating proper exception handling techniques. The chapter emphasizes the use of keywords like try, catch, finally, throw, and throws in managing exceptions effectively.

Uploaded by

babsobatu
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/ 51

Chapter 4: Exception Handling

4.1. Exceptions Overview


4.2. Catching Exceptions
4.3. The finally Block
4.4. Exception Methods
4.5. Declaring Exceptions
4.6. Defining and Throwing Exceptions
4.7. Errors and Runtime Exceptions

8/15/2023 By: Tadessse Kebede(MSc) 1


4.1. Exceptions Overview
▪ Runtime errors occur while a program is running if the
environment detects an operation that is impossible to carry
out. For example, if you access an array using an index out of
bounds, your program will get a runtime error with an
ArrayIndexOutOfBoundsException.
▪ To read data from a file, you need to create a Scanner object
using new Scanner(new File(filename)).
▪ If the file does not exist, your program will get a runtime error
with a FileNotFoundException.
▪ In Java, runtime errors are caused by exceptions.
▪ An exception is an object that represents an error or a
condition that prevents execution from proceeding normally.
▪ If the exception is not handled, the program will terminate
abnormally.
8/15/2023 By: Tadessse Kebede(MSc) 2
4.1. Exception-Handling Overview
▪ An exception is a problem that arises during the execution of a program.
▪ When an Exception occurs the normal flow of the program is disrupted and
the program terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
▪ An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
o A user has entered an 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 or the JVM has run out of
memory.
o Performing illegal arithmetic (division by zero)
o Illegal arguments to methods
o Accessing an out-of-bounds array element
o Hardware failures
o Writing to a read-only file
o Opening a non-existing file
▪ Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
▪ The goals for exception handling in Java are to simplify the creation of large,
reliable programs, and to do so with more confidence that your application doesn’t
have an unhandled error.
8/15/2023 By: Tadessse Kebede(MSc) 3
Example 1:- Quotient.java
1 import java.util.Scanner;
2
3 public class Quotient {
▪ If you entered 0 for the second number, a runtime error 4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
would occur, because you cannot divide an integer by 0. 6
(Recall that a floating-point number divided by 0 does not 7 // Prompt the user to enter two integers
raise an exception.) 8 System.out.print("Enter two integers: ");
▪ A simple way to fix the error is to add an if statement to 9 int number1 = input.nextInt();
10 int number2 = input.nextInt();
test the second number 11
12 System.out.println(number1 + " / " + number2 + " is " +
13 ( number1/number2));
14 }
15 }
Output:
Enter two integers: 5 2
5 / 2 is 2
Enter two integers: 3 0
Exception in thread "main" java.lang.ArithmeticException: / by zero at
Quotient.main

8/15/2023 By: Tadessse Kebede(MSc) 4


Example 2: QuotientWithIf.java
1 import java.util.Scanner;
2
▪ A simple way to fix the error is 3 public class QuotientWithIf {
to add an if statement to test 4 public static void main(String[] args) {
the second number 5 Scanner input = new Scanner(System.in);
6
7 // Prompt the user to enter two integers
8 System.out.print("Enter two integers: ");
9 int number1 = input.nextInt();
10 int number2 = input.nextInt();
11
12 if (number2 != 0)
13 System.out.println(number1 + " / " + number2
14 + " is " + (number1 / number2));
15 else
16 System.out.println("Divisor cannot be zero ");
17 }
18 }
Output:
Enter two integers: 5 0
Divisor cannot be zero
8/15/2023 By: Tadessse Kebede(MSc) 5
QuotientWithException.java

Enter two integers:


Exception: an integer cannot be divided by zero
Execution continues ...
▪ The program contains a try block and a catch block.
▪ The try block (lines 12–18) contains the code that is
executed in normal circumstances.
▪ The catch block (lines 19–22) contains
the code that is executed when number2 is 0.
In this event the program throws an exception
by executing
throw new ArithmeticException("Divisor cannot be zero");

8/15/2023 By: Tadessse Kebede(MSc) 6


Cont’d
▪ The value thrown, in this case new ArithmeticException("Divisor cannot be
zero"), is called an exception.
▪ The execution of a throw statement is called throwing an exception.
▪ The exception is an object created from an exception class.
▪ In this case, the exception class is java.lang.ArithmeticException.
▪ The execution of a throw statement is called throwing an exception.
▪ When an exception is thrown, the normal execution flow is interrupted.
▪ As the name suggests, to “throw an exception” is to pass the exception from
one place to another.
▪ The exception is caught by the catch block. The code in the catch block is executed to
handle the exception.
▪ Afterward, the statement (line 24) after the catch block is executed.
▪ The throw statement is analogous to a method call, but instead of calling a method, it
calls a catch block.

8/15/2023 By: Tadessse Kebede(MSc) 7


Cont’d
▪ In this sense, a catch block is like a method definition with a parameter
that matches the type of the value being thrown.
▪ Unlike a method, after the catch block is executed, however, the program
control does not return to the throw statement; instead, it executes the next
statement after the catch block.
▪ The identifier ex in the catch–block header catch (ArithmeticException ex)
acts very much like a parameter in a method. So this parameter is referred
to as a catch–block parameter.
▪ The type (e.g., ArithmeticException) preceding ex specifies what kind of
exception the catch block can catch.
▪ Once the exception is caught, you can access the thrown value from this
parameter in the body of a catch block.

8/15/2023 By: Tadessse Kebede(MSc) 8


try-throw-catch block
▪ In summary, a template for a try-throw-catch block may look like this:
try {
Code to try;
Throw an exception with a throw statement or
from method if necessary;
More code to try;
}
catch (type ex) {
Code to process the exception;
}

▪ An exception may be thrown directly by using a throw statement in a try


block, or by invoking a method that may throw an exception.

8/15/2023 By: Tadessse Kebede(MSc) 9


Example 3
▪ What is the output of this program?
public class ExceptionExample{
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}
Output:
Exception in thread "main“
java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java)

8/15/2023 By: Tadessse Kebede(MSc) 10


Example 4
▪ For example: if you use FileReader file class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then a
FileNotFoundException occurs, and the compiler prompts the programmer
to handle the exception.
▪ Example:
import java .io.File;
import java.io.FileReader;
Public class FilenotFound_Demo {
public static void main (String args []){
File file = new File("E://file.txt");
FileReader fr =new FileReader(file);
}
}
▪ Output:
In the above program if the file specified is not found then it will
generate FileNotFoundException.
8/15/2023 By: Tadessse Kebede(MSc) 11
Exception keywords
▪ Five keywords are used in exception handling:
o try – a block surrounding program statements to monitor for
exceptions
o catch – together with try, catches specific kinds of exceptions
and handles them in some way
o finally – specifies any code that absolutely must be executed
whether or not an exception occurs
o throw – used to throw a specific exception from the program
o throws – specifies which exceptions a given method can throw

8/15/2023 By: Tadessse Kebede(MSc) 12


Exception handling block
▪ Syntax:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }

finally { … }
▪ where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the
exception Exception
3) finally { … } is the block of code to execute before the try
block ends

8/15/2023 By: Tadessse Kebede(MSc) 13


Java’s exception-handling model
▪ Exception handling in Java consists of declaring exceptions, throwing
exceptions, and catching and processing exceptions.

8/15/2023 By: Tadessse Kebede(MSc) 14


Exception-handling Example 1: QuotientWithMethod.java

Output
Enter two integers: 5 3
5 / 3 is 1
Execution continues ...
Enter two integers: 5 0
Exception: an integer cannot be divided by zero
8/15/2023 By: Tadessse Kebede(MSc) Execution continues ... 15
Exception-handling Example 2: FileNotFoundExceptionDemo.java

▪ The program creates a Scanner for a


file (line 12).
▪ If the file does not exist, the
constructor throws a
FileNotFoundException, which is
caught in the catch block

8/15/2023 By: Tadessse Kebede(MSc) 16


Exception-handling Example 3: InputMismatchExceptionDemo.java

▪ When executing input.nextInt() (line 11), an


InputMismatchException occurs if the input
entered is not an integer.
▪ Suppose 3.5 is entered.
▪ An InputMismatchException occurs and the
control is transferred to the catch block.
▪ The statements in the catch block are now
executed.
▪ The statement input.nextLine() in line 22
discards the current input line so that the
user can enter a new line of input.
▪ The variable continueInput controls the
loop.
▪ Its initial value is true (line 6), and it is
changed to false (line 17) when a valid input
is received.
8/15/2023 By: Tadessse Kebede(MSc) 17
Exception Types
▪ There are two types of Exceptions:
▪ Built-in Exceptions: are exceptions which are handled by the
java compiler. This is classified into checked and unchecked
▪ Checked Exceptions: are the objects of the exception class or
any of its sub-class except Runtime Exception class.
▪ They are invalid conditions and we can’t write any condition
for such exception
▪ Unchecked Exceptions are exceptions that are the sub-classes
of Runtime Exception class.
▪ They are valid conditions and we can write a condition for such
exception
▪ User-defined Exceptions: are exceptions types created by the
user program.

8/15/2023 By: Tadessse Kebede(MSc) 18


Unchecked Exceptions
▪ The compiler does not check if a method handles or throws
there exceptions
▪ Usually occur because of programming errors, when code is not
robust enough to prevent them
▪ They are numerous and can be ignored by the programmer
▪ Some of the common unchecked exceptions include:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException
3. ArrayStoreException
4. ClassCastException
5. IllegalStateException
6. IllegalMonitorStateException
7. IllegalArgumentException

8/15/2023 By: Tadessse Kebede(MSc) 19


Checked Exceptions
▪ These exceptions must be included in the method’s throws
clause if the method generates but does not handle them.
▪ Usually occur because of errors programmer cannot control:
examples: hardware failures, unreadable files.
▪ They are less frequent and they cannot be ignored by the
programmer . Some of the checked exceptions are:
1.NoSuchMethodException
2.FileNotFoundException
3.InterruptedException
4.InstantiationException
5.IllegalAccessException
6.CloneNotSupportedException
7.ClassNotFoundException

8/15/2023 By: Tadessse Kebede(MSc) 20


Exception Types … Cont’d
▪ 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.

8/15/2023 By: Tadessse Kebede(MSc) 21


System errors
▪ Are thrown by the JVM and represented in the Error class.
▪ The Error class describes internal system errors. Such errors
rarely occur.
▪ If one does, there is little you can do beyond notifying the user
and trying to terminate the program gracefully.
Class Possible Reason for Exception

LinkageError A class has some dependency on another


class, but the latter class has
changed incompatibly after the
compilation of the former class.
VirtualMachineError The JVM is broken or has run out of the
resources it needs in order to
continue operating.

8/15/2023 By: Tadessse Kebede(MSc) 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.
Class Possible Reason for Exception

ClassNotFoundException Attempt to use a class that does not exist. This exception would occur,
for example, if you tried to run a nonexistent class using the java
command, or if your program were composed of, say, three class
files, only two of which could be found.

IOException Related to input/output operations, such as invalid input, reading past


the end of a file, and opening a nonexistent file. Examples of subclasses
of IOException are InterruptedIOException,
EOFException (EOF is short for End Of File), and FileNot-
FoundException.

8/15/2023 By: Tadessse Kebede(MSc) 23


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.
Class Possible Reason for Exception

ArithmeticException Dividing an integer by zero. Note that floating-point arithmetic


does not throw exceptions. See Appendix E, “Special
Floating-Point Values.”

NullPointerException Attempt to access an object through a null reference variable.


IndexOutOfBoundsException Index to an array is out of range.

IllegalArgumentException A method is passed an argument that is illegal or inappropriate.

8/15/2023 By: Tadessse Kebede(MSc) 24


Exception Types….
▪ 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 most cases, unchecked exceptions reflect programming logic errors that
are unrecoverable.
▪ For example, a NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to it; an
IndexOutOfBoundsException is thrown if you access an element in an
array outside the bounds of the array.
▪ These are logic errors that should be corrected in the program.
▪ Unchecked exceptions can occur anywhere in a program.
▪ To avoid cumbersome overuse of try-catch blocks, Java does not mandate
that you write code to catch or declare unchecked exceptions.

8/15/2023 By: Tadessse Kebede(MSc) 25


4.2. Catching Exceptions
▪ All exception classes are subtypes of the java.lang.Exception
class.
▪ The Exception class is a subclass of the Throwable class.
▪ Other than the Exception class there is another subclass called
Error which is derived from the Throwable class.
▪ The Exception class has two main subclasses: IOException
class and RuntimeException Class.
▪ 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.

8/15/2023 By: Tadessse Kebede(MSc) 26


Catching Exceptions Syntax
▪ Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following.
▪ Syntax:
try {
// Protected code
}
catch (ExceptionName e1) {
// Catch block
}
▪ The code which is prone to exceptions is placed in the try block.
▪ When an exception occurs, that exception occurred is handled by catch block
associated with it. Every try block should be immediately followed either by a catch
block or finally 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.
▪ If the type of exception that occurred is listed in a catch block, the exception is passed
to the catch block.
8/15/2023 By: Tadessse Kebede(MSc) 27
Syntax for multiple catch blocks
▪ The following is an array declared with 2 elements. Then the code tries to access the 3 of
element of the array which throws an exception.
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
….
catch (ExceptionN exVar3) {
handler for exceptionN;
}
▪ You can have any number of catch blocks after a single try. If an exception occurs in the protected
code, the exception is thrown to the first catch block in the list. If the data type of the exception
thrown matches Exception1, it gets caught there. If not, the exception passes down to the second
catch statement. This continues until the exception either is caught or falls through all catches.
8/15/2023 By: Tadessse Kebede(MSc) 28
Cont’d
▪ If no exceptions arise during the execution of the try block, the catch blocks are
skipped.
▪ If one of the statements inside the try block throws an exception, Java skips the
remaining statements in the try block and starts the process of finding the code to
handle the exception.
▪ The code that handles the exception is called the exception handler; it is found by
propagating the exception backward through a chain of method calls, starting from the
current method.
▪ Each catch block is examined in turn, from first to last, to see whether the type of the
exception object is an instance of the exception class in the catch block.
▪ If so, the exception object is assigned to the variable declared, and the code in the catch
block is executed.
▪ If no handler is found, Java exits this method, passes the exception to the method that
invoked the method, and continues the same process to find a handler.
▪ If no handler is found in the chain of methods being invoked, the program terminates
and prints an error message on the console.
▪ The process of finding a handler is called catching an exception.
8/15/2023 By: Tadessse Kebede(MSc) 29
Cont’d
▪ Suppose the main method invokes method1, method1 invokes method2, method2 invokes method3, and
method3 throws an exception, as shown in Figure Consider the following scenario:
▪ If the exception type is Exception3, it is caught by the catch block for handling exception ex3 in method2.
statement5 is skipped, and statement6 is executed.
▪ If the exception type is Exception2, method2 is aborted, the control is returned to method1, and the
exception is caught by the catch block for handling exception ex2 in method1. statement3 is skipped, and
statement4 is executed.
▪ If the exception type is Exception1, method1 is aborted, the control is returned to the main method, and
the exception is caught by the catch block for handling exception ex1 in the main method. statement1 is
skipped, and statement2 is executed.
▪ If the exception type is not caught in method2, method1, and main, the program terminates. statement1
and statement2 are not executed.

8/15/2023 By: Tadessse Kebede(MSc) 30


Catching Exceptions Example:
▪ The following is an array declared with 2 elements. Then the code tries to access the 3
of element of the the array which throws an exception.
import java .io.*;
public class ExcepTest {
public static void main (String args []) {
try {
int a [] = new int[2];
System.outout.println(“Access element three :" + a [3]);
}
catch(ArrayIndexOutOfBoundsException e ){
System.outout.println("Exception thrown :" + e );
}
System.outout.println("Out of the block");
}
}
▪ This will produce the following output
▪ Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
8/15/2023 By: Tadessse Kebede(MSc) 31
Throwing Exceptions
▪ A program that detects an error can create an instance of an appropriate exception type and
throw it.
▪ This is known as throwing an exception.
▪ Here is an example: Suppose the program detects that an argument passed to the method
violates the method contract (e.g., the argument must be nonnegative, but a negative argument
is passed); the program can create an instance of IllegalArgumentException and throw it, as follows:
IllegalArgumentException ex =
new IllegalArgumentException("Wrong Argument");
throw ex;
Or, if you prefer, you can use the following:
throw new IllegalArgumentException("Wrong Argument");

8/15/2023 By: Tadessse Kebede(MSc) 32


Example: Declaring, Throwing, and Catching Exceptions
▪ This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method
in the Circle class, Circle3.java.
▪ The new setRadius method throws an exception if the radius is negative.
▪ Rename the circle class given in as CircleWithException, which is the same as Circle3 except that the
setRadius(double newRadius) method throws an IllegalArgumentException if the argument newRadius is
negative.

8/15/2023 By: Tadessse Kebede(MSc) 33


Example: Declaring, Throwing, and Catching Exceptions

8/15/2023 By: Tadessse Kebede(MSc) 34


4.3. The finally Block
▪ 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.
▪ Occasionally, you may want some code to be executed
regardless of whether an exception occurs or is caught.
▪ Java has a finally clause that can be used to accomplish this
objective.
▪ The syntax for the finally clause might look like this:
try {
statements;
}
catch (TheException ex) {
handling ex;
}
finally {
finalStatements;
8/15/2023
} By: Tadessse Kebede(MSc) 35
The code under finally Block…
▪ The code in the finally block is executed under all
circumstances, regardless of whether an exception occurs in
the try block or is caught. Consider three possible cases:
o If no exception arises in the try block, finalStatements is executed, and
the next statement after the try statement is executed.
o If a statement causes an exception in the try block that is caught in a
catch block,the rest of statements in the try block are skipped, the catch
block is executed, and the finally clause is executed. The next statement
after the try statement is executed.
o If one of the statements causes an exception that is not caught in any
catch block,the other statements in the try block are skipped, the finally
clause is executed, and the exception is passed to the caller of this
method.
▪ The finally block executes even if there is a return statement
prior to reaching the finally block.
▪ A common use of the finally clause is in I/O programming
8/15/2023 By: Tadessse Kebede(MSc) 36
finally Block Example: FinallyDemo.java

▪ The statements in lines 7 and 10 may throw an IOException, so they are placed inside a try
block.
▪ The statement output.close() closes the PrintWriter object output in the finally block.
▪ This statement is executed regardless of whether an exception occurs in the try block or is
8/15/2023 caught. By: Tadessse Kebede(MSc) 37
Note the following:
▪ A catch clause cannot exist without a try statement.
▪ It is not compulsory to have finally clauses whenever a
try/catch block is present.
▪ The try block cannot be present without either catch clause or
finally clause.
▪ Any code cannot be present in between the try, catch, finally
blocks.

8/15/2023 By: Tadessse Kebede(MSc) 38


4.4. Exception Methods
▪ public String getMessage(): Returns a detailed message about
the exception that has occurred.
▪ public Throwable getCause(): Returns the cause of the
exception.
▪ public String toString(): Returns the name of the class
concatenated with the result of getMessage().
▪ public void printStackTrace(): Prints the result of toString().
▪ public StackTraceElement [] getStackTrace(): Returns an array
containing each element on the stack trace.
▪ public Throwable fillInStackTrace(): Fills the stack trace of this
Throwable object with the current stack trace.

8/15/2023 By: Tadessse Kebede(MSc) 39


4.5. Declaring Exceptions
▪ In Java, the statement currently being executed belongs to a method.
▪ The Java interpreter invokes the main method to start executing a program.
▪ Every method must state the types of checked exceptions it might throw.
▪ This is known as declaring exceptions.
▪ Because system errors and runtime errors can happen to any code, Java
does not require that you declare Error and RuntimeException (unchecked
exceptions) explicitly in the method.
▪ However, all other exceptions thrown by the method must be explicitly
declared in the method header so that the caller of the method is informed of
the exception.
▪ We can define our own Exception class as below:
class MyException extends Exception { //for checked exceptions
}
modifier MyException extends RuntimeException { //for runtime exceptions
}

8/15/2023 By: Tadessse Kebede(MSc) 40


4.5. Declaring Exceptions…
▪ To declare an exception in a method, use the throws keyword in the
method header, as in this example:
public void myMethod() throws IOException
▪ The throws keyword indicates that myMethod might throw an
IOException.
▪ If the method might throw multiple exceptions, add a list of the
exceptions, separated by commas, after
throws:
public void myMethod()
throws Exception1, Exception2, ..., ExceptionN

8/15/2023 By: Tadessse Kebede(MSc) 41


4.6. Defining and Throwing Exceptions
▪ A program that detects an error can create an instance of an appropriate
exception type and throw it. This is known as throwing an exception.
▪ It is important to understand how to throw exceptions in Java.
▪ This will allow you to create higher quality code where errors are checked at
compile time instead of runtime, and create custom exceptions that make
debugging and recovery easier.
▪ Throwing an exception is as simple as using the "throw" statement. You
then specify the Exception object you wish to throw.
▪ Every Exception includes a message which is a human readable error
description.
▪ It can often be related to problems with user input, server, backend, etc.
▪ Here is an example that shows how to throw an exception:
throw new Exception("Exception message");

8/15/2023 By: Tadessse Kebede(MSc) 42


The Throws keyword
▪ 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.
▪ A method can declare that it throws more than one exception, in which case
the exceptions are declared in a list separated by commas.
▪ The throws keyword allows the compiler to help you write code that handles
this type of error, but it does not prevent the abnormal termination of the
program.
▪ With the help of the throws keyword, we can provide information to the
caller of the method about the types of exceptions the method might throw.
▪ The caller has to handle the exception using a try catch block or propagate
the exception.

8/15/2023 By: Tadessse Kebede(MSc) 43


Defining and Throwing Exceptions Example

import java.io.*; This must be handled with a try/catch block:


public class className { public class Example {
public void withdraw (double amount ) throws RemoteException, public static void main(String[] arg) {
InsufficientFundsException { try {
// Method implementation testMethod();
} } catch (Exception e) {
// Remainder of class definition e.printStackTrace();
} }
In the example below, we have created a test method to demonstrate }
throwing an exception. The toString() method returns a textual }
representation of an object, but in this case the variable is null. Calling a
method on a null reference or trying to access a field of a null reference
will trigger a NullPointerException.
public void testMethod() throws Exception {
String test = null;
test.toString();
}
8/15/2023 By: Tadessse Kebede(MSc) 44
4.7. Errors and Runtime Exceptions
▪ 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.
▪ Errors are abnormal conditions that happen in case of severe failures, these
are not handled by the Java programs.
▪ Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory.
▪ A logical error is always the symptom of a bug in application code leading to
incorrect output e.g. subtracting two variables instead of adding them.
▪ In case of a logical error, the program operates incorrectly but does not
terminate abnormally.
▪ Each statement may need to be checked to identify a logical error, which
makes it generally harder to debug than a runtime error.

8/15/2023 By: Tadessse Kebede(MSc) 45


4.7. Errors and Runtime Exceptions…
▪ A runtime error in Java is an application error that occurs
during the execution of a program.
▪ A runtime error occurs when a program is syntactically correct
but contains an issue that is only detected during program
execution.
▪ These issues cannot be caught at compile time by the Java
compiler and are only detected by the Java Virtual Machine
(JVM) when the application is running. Runtime errors are a
category of exception that contains several more specific error
types.
▪ Some of the most common types of runtime errors are:
o IO errors
o Division by zero errors
o Out of range errors
o Undefined object errors, etc..
8/15/2023 By: Tadessse Kebede(MSc) 46
4.7. Errors and Runtime Exceptions…
▪ Runtime errors occur during program execution (the
interpretation phase), after compilation has taken place.
▪ Any code that throws a runtime error is therefore syntactically
correct.
▪ A runtime error could potentially be a legitimate issue in code,
for example, incorrectly formatted input data or lack of
resources (e.g. insufficient memory or disk space).
▪ When a runtime error occurs in Java, the compiler specifies the
lines of code where the error is encountered.
▪ This information can be used to trace back where the problem
originated.
▪ It is useful to catch runtime exceptions and continue program
execution. To handle a runtime error, the code can be placed
within a try catch block and the error can be caught inside the
8/15/2023 catch block. By: Tadessse Kebede(MSc) 47
Runtime Exceptions Example: Division by zero error
▪ Here is an example of a java.lang.ArithmeticException, a type
of runtime exception, thrown due to division by zero:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a = 10, b = 0;
System.out.println("Result: "+ a/b);
}
}
▪ In this example, an integer a is attempted to be divided by
another integer b, whose value is zero, leading to a
java.lang.ArithmeticException:

8/15/2023 By: Tadessse Kebede(MSc) 48


Runtime Exceptions Example: OutOfBoundsExceptionthrown
▪ Here is an example of a :
java.lang.ArrayIndexOutOfBoundsExceptionthrown due to an
attempt to access an element in an array that is out of bounds:
public class ValueOutOfRangeErrorExample {
public static void main(String[] args) {
int arr[] = new int[5];
System.out.println("5th element in array: " + arr[5]);
}
}
▪ In this example, an array is initialized with 5 elements. An
element at position 5 is later attempted to be accessed in the
array, which does not exist, leading to a
java.lang.ArrayIndexOutOfBoundsException runtime error:

8/15/2023 By: Tadessse Kebede(MSc) 49


How to handle Runtime Exceptions
▪ To illustrate this, the code in the earlier ArithmeticException example can
be updated as follows:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
System.out.println("Result: " + a/b);
} catch (ArithmeticException ae) {
System.out.println("Arithmetic Exception: cannot divide by 0");
}
}
}
▪ Surrounding the code in try catch blocks like the above allows the program
to continue execution after the exception is encountered.
▪ Runtime errors can be avoided where possible by paying attention to detail
and making sure all statements in code are mathematically and logically
correct.
8/15/2023 By: Tadessse Kebede(MSc) 50
End-of-Chapter-4

8/15/2023 By: Tadessse Kebede(MSc) 51

You might also like