Академический Документы
Профессиональный Документы
Культура Документы
Exception Handling
Budditha Hettige Department of Statistics and Computer Science
Budditha Hettige 1
Budditha Hettige
Errors
Errors can be categorized as several ways;
Syntax Errors Logical Errors Runtime Errors
Budditha Hettige
Syntax Errors
Error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language All syntax errors can be reliably detected until run-time Many Syntax errors can be detected at compile-time
Budditha Hettige
Budditha Hettige
Error description
You must have a good working knowledge of error messages to discover the cause of the error
Budditha Hettige 6
Logical Errors
Errors that indicate the logic used when coding the program failed to solve the problem You do not get error messages with logic errors Your only clue to the existence of logic errors is the production of wrong solutions
Budditha Hettige
Results
Budditha Hettige
Runtime Errors
low-level errors
dereference of a null pointer out-of-bounds array access divide by zero attempt to open a non-existent file for reading bad cast (e.g., casting an Object that is actually a Boolean to Integer)
higher-level
call to Stack's "pop" method for an empty stack call to "factorial" function with a negative number call to List's nextElement method when hasMoreElements is false
Budditha Hettige 10
Programmer error
These errors should be detected as early as possible to provide good feedback.
Budditha Hettige 11
Language level.
Type conversion; illegal values, improper casts. Bounds violations; illegal array indices. Bad references; null pointers.
Program level.
User defined exceptions.
Budditha Hettige 12
Use a reference parameter or a global variable to hold an error code Use exceptions. This seems to be the method of choice for modern programming languages.
Budditha Hettige 13
What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Example
Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted
Budditha Hettige 14
Example
Divide by zero
class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(Pls. print me.); } }
Where the error Error Message is occured Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3)
Budditha Hettige
15
Budditha Hettige
16
Budditha Hettige
17
Budditha Hettige
18
Budditha Hettige
19
If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates and uses the default exception handler
Budditha Hettige 20
Budditha Hettige
21
Budditha Hettige
22
Advantages
Separating Error-Handling code from regular business logic code Propagating errors up the call stack Grouping and differentiating error types
Budditha Hettige
23
Budditha Hettige
24
Budditha Hettige
25
Catching Exceptions
try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> }
Budditha Hettige
26
Example
Budditha Hettige
27
Multiple catch
Budditha Hettige
28
Try {
Catch {
Catch {
Example
1. Execute This
3. Execute This
Budditha Hettige 30
Budditha Hettige
31
Exception thrown was not specified in any catch block in the method
Budditha Hettige 33
Finally() { }
matching catch
finally
Budditha Hettige
next step
35
Throwing Exceptions
Java allows you to throw exceptions (generate exceptions)
throw <exception object>;
Example:
throw new ArithmeticException(testing...);
Budditha Hettige 36
If a method may cause an exception to occur but does not catch it, then it must say so using the throws keyword
Applies to checked exceptions only Syntax:
<type> <methodName> (<parameterList>) throws <exceptionList> { <methodBody> }
Budditha Hettige 37
Budditha Hettige
38
Budditha Hettige
39
Budditha Hettige
40
Exception class
Conditions that user programs can reasonably deal with Usually the result of some flaws in the user program code Examples
Division by zero error Array out-of-bounds error
Budditha Hettige
41
Budditha Hettige
42
Budditha Hettige
43
Sample Code
class TestHateString { public static void main(String args[]) { String input = "invalid input"; try { if (input.equals("invalid input")) { throw new HateStringExp(); } System.out.println("Accept string."); } catch (HateStringExp e) { System.out.println("Hate string!); } class HateStringExp extends RuntimeException } { } /* some code */
}
Budditha Hettige 45
Example
public class CustomExceptionTest { public static void main(String[] args) throws Exception { int age = getAge(); if (age < 0) {
46
Exception class
public class NegativeAgeException extends Exception { private int age; public NegativeAgeException(int newAge) { age = newAge; } public String toString() { return "Age cannot be negative" + " " +age ; } }
Budditha Hettige 47