47
CSC 308 2.0 System Development with Java Budditha Hettige Department of Statistics and Computer Science 1 Exception Handling Budditha Hettige

Exception Handling - WordPress.com · What Is an Exception? •An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

CSC 308 2.0

System Development with Java

Budditha Hettige

Department of Statistics and Computer Science

1

Exception Handling

Budditha Hettige

2 Budditha Hettige

Errors

• Errors can be categorized as several ways;

– Syntax Errors

– Logical Errors

– Runtime Errors

3 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

4 Budditha Hettige

Common Java syntax errors

• Capitalization of key words

Line xx: class or interface declaration expected

• Writing a string over a new line

Line xx: ';' expected

• Missing brackets in a no-argument message

Line xx: Invalid expression statement

• Forgetting to import a package

Line nn: Method yyyy not found in class xxxx.

5 Budditha Hettige

Syntax Error correction

1. Go to the error line

2. Identify the error

3. Correct the error

• You must have a good working knowledge of error messages to discover the cause of the error

6

Error line Error line

Error description Error description

Budditha Hettige

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

7 Budditha Hettige

Common Logic Errors in Java

• Using a variable before it is given a value

int x;

x = x + 1;

System.out.println("X = " + x);

• Misplaced Semi-colon (usually with a loop or if statement) if ( x > y) ; {

System.out.println("X is bigger");

}

• Confusing the equivalence operator == with the assignment operator =

8 Budditha Hettige

Logical error correction

• Debugging can be used to find what the logical

errors in your program

9

Debug line Debug line

Results 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

10 Budditha Hettige

Runtime Errors contd..

Errors can arise due to

• User error

– providing a bad file name or a poorly formatted

input file

• Programmer error

– These errors should be detected as early as

possible to provide good feedback.

11 Budditha Hettige

Exceptions can occur at many

levels

• Hardware/operating system level.

• Arithmetic exceptions; divide by 0, under/overflow.

• Memory access violations; segfault, stack over/underflow.

• Language level.

• Type conversion; illegal values, improper casts.

• Bounds violations; illegal array indices.

• Bad references; null pointers.

• Program level.

• User defined exceptions.

12 Budditha Hettige

Ways to handle errors

• Write an error message and quit.

– This doesn't provide any recovery

• Return a special value to indicate that an error occurred

– calling code check for an error. This can reduce the efficiency of the code

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

13 Budditha Hettige

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

14 Budditha Hettige

Example

class DivByZero {

public static void main(String args[]) {

System.out.println(3/0);

System.out.println(“Pls. print me.”);

}

}

Error Message

Exception in thread "main"

java.lang.ArithmeticException: / by zero at

DivByZero.main(DivByZero.java:3)

15

Divide by zero Divide by zero

Where the error is occured

Where the error is occured

Budditha Hettige

Default exception handler

1. Provided by Java runtime

2. Prints out exception description

3. Prints the stack trace

4. Hierarchy of methods where the exception occurred

5. Causes the program to terminate

16

Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3

Budditha Hettige

What Happens When an Exception

Occurs?

17 Budditha Hettige

When an Exception Occurs?

• When an exception occurs within a method,

the method creates an exception object and

hands it off to the runtime system

– Creating an exception object and handing it to the

runtime system is called “throwing an exception”

– Exception object contains information about the

error, including its type and the state of the

program when the error occurred

18 Budditha Hettige

When an Exception Occurs? (1)

• The runtime system searches the call stack for

a method that contains an exception handler

19 Budditha Hettige

When an Exception Occurs? (2)

• When an appropriate handler is found, the runtime system passes the exception to the handler

– An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler

– The exception handler chosen is said to catch the exception.

• 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

20 Budditha Hettige

Searching the Call Stack for

an Exception Handler

21 Budditha Hettige

22

How exception handler works?

Exception "thrown" here

Exception handler

Exception handler

Thrown exception matched against first set of exception handlers

Thrown exception matched against first set of exception handlers

If it fails to match, it is matched against next set of handlers, etc.

If it fails to match, it is matched against next set of handlers, etc.

If exception matches none of handlers, program is abandoned

If exception matches none of handlers, program is abandoned

Budditha Hettige

Advantages

• Separating Error-Handling code from

“regular” business logic code

• Propagating errors up the call stack

• Grouping and differentiating error types

23 Budditha Hettige

Java Exception Handling

• A method can duck any exceptions thrown within it,

thereby allowing a method farther up the call stack to

catch it. Hence, only the methods that care about

errors have to worry about detecting errors

• Any checked exceptions that can be thrown within a

method must be specified in its throws clause

24 Budditha Hettige

Grouping and Differentiating

Error Types

• Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy

• An example of a group of related exception classes in the Java platform are those defined in java.io – IOException and its descendants

– IOException is the most general and represents any type of error that can occur when performing I/O

– Its descendants represent more specific errors. For

– example, • FileNotFoundException means that a file could not be located on

disk.

25 Budditha Hettige

Catching Exceptions

try

{

<code to be monitored for exceptions>

}

catch (<ExceptionType1> <ObjName>)

{

<handler if ExceptionType1 occurs>

}

...

}

catch (<ExceptionTypeN> <ObjName>)

{

<handler if ExceptionTypeN occurs>

}

26 Budditha Hettige

Example

27 Budditha Hettige

Multiple catch

28 Budditha Hettige

How try and catch works?

29

Try { }

Try { }

Catch { }

Catch { }

Catch { }

Catch { }

Statement after the last catch

NO Match

Leaves the method

Budditha Hettige

Example

30

1. Execute This 1. Execute This

2. Goto this catch()

2. Goto this catch()

3. Execute This 3. Execute This

Budditha Hettige

No any catch for matching ???

31 Budditha Hettige

Catching Exceptions with finally

Syntax: try

{

<code to be monitored for exceptions>

}

catch (<ExceptionType1> <ObjName>)

{

<handler if ExceptionType1 occurs>

} ...

}

finally

{

<code to be executed before the try block ends>

}

32 Budditha Hettige

Catching Exceptions the finally Keyword

• Block of code is always executed despite of different scenarios:

– Forced exit occurs using a return, a continue or a break statement

– Normal completion

– Caught exception thrown

• Exception was thrown and caught in the method

– Uncaught exception thrown

• Exception thrown was not specified in any catch block in the method

33 Budditha Hettige

How try and catch –finaly works?

34

Try { }

Try { }

Catch { }

Catch { }

Catch { }

Catch { }

Statement after the last catch

NO Match

Finally() { }

Budditha Hettige

35

Sequence of Events for finally clause

Preceding step

try block

throw statement

matching catch

next step

finally

Budditha Hettige

Throwing Exceptions

• Java allows you to throw exceptions (generate exceptions)

– throw <exception object>;

• An exception you throw is an object

– You have to create an exception object in the same way

– you create any other object

• Example:

– throw new ArithmeticException(“testing...”);

36 Budditha Hettige

Rules in Exception Handling

• A method is required to either catch or list all exceptions it might throw – Except for Error or RuntimeException, or their subclasses

• 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>

}

37 Budditha Hettige

38

Sequence of Events for No throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Budditha Hettige

39

Sequence of Events for throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Budditha Hettige

The exception hierarchy

40 Budditha Hettige

The Error and Exception Classes

• Throwable class

– Root class of exception classes

– Immediate subclasses

• Error

• Exception

• 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

41 Budditha Hettige

The Error and Exception Classes

• Error class

– Used by the Java run-time system to handle errors

occurring in the run-time environment

– Generally beyond the control of user programs

– Examples

• Out of memory errors

• Hard disk crash

42 Budditha Hettige

User define Exception

43 Budditha Hettige

Creating Your Own Exception Class

• Steps to follow

– Create a class that extends the RuntimeException or the Exception class

– Customize the class

• Members and constructors may be added to the class

– Example: class HateStringExp extends RuntimeException

{

/* some code */

}

44 Budditha Hettige

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!”);

}

}

}

45

class HateStringExp extends RuntimeException

{

/* some code */

}

class HateStringExp extends RuntimeException

{

/* some code */

}

Budditha Hettige

Example

public class CustomExceptionTest

{

public static void main(String[] args) throws Exception

{

int age = getAge();

if (age < 0)

{

throw new NegativeAgeException(age);

}

Else

{

System.out.println("Age entered is " + age);

}

}

static int getAge()

{

return -10;

}

} 46 Budditha Hettige

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 ;

}

}

47 Budditha Hettige