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

java Chapter 6 Exceptions

exception

Uploaded by

benyias2016
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

java Chapter 6 Exceptions

exception

Uploaded by

benyias2016
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

CHAPTER SIX

Handling Errors with Exceptions

1
Introduction
• Users have high expectations for the code we
produce.
• Users may use our programs in unexpected
ways.
• Due to design errors or coding errors, our
programs may fail in unexpected ways during
execution

2
Introduction
• It is our responsibility to produce quality code that does
not fail unexpectedly.
• Consequently, we must design error handling into our
programs.
• In many cases, handling an exception allows a program to
continue executing as if no problem had been
encountered.
• A more severe problem could prevent a program from
continuing normal execution, instead requiring it to notify
the user of the problem before terminating in a controlled
manner
3
Errors and Error Handling
• An Error is any unexpected result obtained from a
program during execution.
• Unhandled errors may manifest themselves as
incorrect results or behavior, or as abnormal
program termination.
• Errors should be handled by the programmer, to
prevent them from reaching the user.

4
Errors and Error Handling
• Some typical causes of errors:
– Memory errors (Example. memory incorrectly
allocated, memory leaks, “null pointer”)
– File system errors (e.g. disk is full, disk has been
removed)
– Network errors (e.g. network is down, URL does not
exist)
– Calculation errors (e.g. divide by 0)
– Array errors (i.e. accessing element –1)
– Conversion errors (e.g . convert ‘q’ to a number)
5
Attack of the Exception
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

• What happens when this method is used to take


the average of an array of length zero?
• Program throws an Exception and fails
java.lang.ArithmeticException: / by zero
6
What is an Exception?

• An error event that disrupts the program


flow and may cause a program to fail.

• Some examples:
– Performing illegal arithmetic
– Illegal arguments to methods
– Accessing an out-of-bounds array element
– Hardware failures
– Writing to a read-only file
7
Another Exception Example

• 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:4)
8
Exception Message Details

Exception message format:


[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

• What exception class? ArrayIndexOutOfBoundsException


• Which array index is out of bounds? 2
• What method throws the exception? main
• What file contains the method? ExceptionExample.java
• What line of the file throws the exception? 9 4
Exception Handling

• Use a try-catch block to handle


exceptions that are thrown

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}

10
Exception Handling Example

public static int average(int[] a) {


int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

public static void printAverage(int[] a) {


try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
} 11
Catching Multiple Exceptions

• Handle multiple possible exceptions by


multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
} 12
Example

13
Example

14
Program with Exception
handled

15
16
Exceptions Terminology

• When an exception happens we say it


was thrown or raised

• When an exception is dealt with, we


say the exception is was handled or
caught
17
Unchecked Exceptions
• All the exceptions we've seen so far have
been Unchecked Exceptions, or Runtime
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
18
Common Unchecked Exceptions
• ArithmeticException
When an exception arithmetic condition occurs

• ArrayIndexOutOfBoundsException
Processing array with index out of range

• NullPointerException
When object try to process object containing null value

• IllegalArgumentException
method argument is improper is some way
19
Checked Exceptions

• There are also Checked Exceptions

• 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 . . .
20
Dealing With Checked Exceptions
• Every method must catch (handle) checked
exceptions or specify that it may throw them
• Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
}

21
Exception Class Hierarchy
 All exceptions are instances of classes
that are subclasses of Exception
Exception

RuntimeException IOException SQLException

ArrayIndexOutOfBounds FileNotFoundException

NullPointerException MalformedURLException

IllegalArgumentException SocketException

etc. etc.
22
Unchecked Exceptions Checked Exceptions
Checked and Unchecked Exceptions

Checked Exception Unchecked Exception


not subclass of subclass of
RuntimeException RuntimeException
represent invalid conditions in Represent defects in the
areas outside the immediate program (bugs)
control of the program
for errors that the for errors that the
programmer cannot programmer can directly
directly prevent from prevent from occurring,
occurring
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentException,
23
SocketException IllegalStateException
Finally Block
• Programs that obtain certain types of resources must
return them to the system explicitly to avoid so-called
resource leaks.
• Resource-release code typically is placed in a finally
block.
• The finally block is optional.
• If it is present, it is placed after the last catch block.
• Java guarantees that a provided finally block will
execute whether or not an exception is thrown in the
corresponding try block or any of its corresponding
24
Finally Block cont…
• If an exception that occurs in the try block cannot be
caught by one of that try block’s associated catch
handlers, the program skips the rest of the try block
and control proceeds to the finally block, which
releases the resource.
• Then the program passes to the next outer try block
normally in the calling method

25
Finally Block cont…
• In programming languages such as C and C++, the
most common kind of resource leak is a memory leak.
• Java performs automatic garbage collection of memory
no longer used by programs, thus avoiding most
memory leaks.
• However, other types of resource leaks can occur.
• For example, files, database connections and network
connections that are not closed properly might not be
available for use in other programs

26
27
Keyword Summary

• Four new Java keywords

• try and catch – used to handle


exceptions that may be thrown

• throws – to specify which exceptions a


method throws in method declaration

• throw – to throw an exception


28
Exercise
• Write java program with function called “div”
that return division of the first argument by
second argument
• In main method invoke the above method
with two argument taken from user and
display the result
• Try to handle an error incase
arithmeticException occur (incase the second
argument is zero)
29

You might also like