exception handling - wordpress.com · java exception handling • a method can duck any exceptions...

24
Object Oriented Programming Exception H andling Budditha Hettige Department of Computer Science

Upload: others

Post on 31-May-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Object Oriented Programming

Exception Handling

Budditha Hettige

Department of Computer Science

Page 2: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Programming Errors

Types

Syntax Errors

Logical Errors

Runtime Errors

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

2

Page 3: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

• Forgetting to import a package

3

Page 4: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

• Debugging is a way to solve logical errors

– Insert breakpoint(s)

– Debug your code

– Check variable values at run time

4

Page 5: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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 =

5

Page 6: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

6

Page 7: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Runtime Errors contd..

Errors can arise due to

• User error

– providing a bad file name or a poorly formatted

input file

– Enter invalid input (Type)

• Programmer error

– These errors should be detected as early as

possible to provide good feedback.

7

Page 8: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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.

8

Page 9: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

9

Page 10: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

10

Page 11: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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)

11

Divide by zero

Where the error is occurred

Page 12: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Default exception handler (Java)

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

12

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

Page 13: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

13

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

Page 14: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

14

Page 15: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Java exception hierarchy

15

Page 16: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Catching Exceptions

try

{

<code to be monitored for exceptions>

}

catch (<ExceptionType1> <ObjName>)

{

<handler if ExceptionType1 occurs>

}

...

}

catch (<ExceptionTypeN> <ObjName>)

{

<handler if ExceptionTypeN occurs>

}

16

Page 17: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Example

17

Page 18: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Multiple catch

18

Page 19: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

How try and catch works?

19

Try{

}

Catch{

}

Catch{

}

Statement after the last catch

NO Match

Leaves the method

Page 20: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

Example

20

1. Execute This

2. Go to this catch()

3. Execute This

Page 21: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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>

}

21

Page 22: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

22

Page 23: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

How try and catch –finaly works?

23

Try{

}

Catch{

}

Catch{

}

Statement after the last catch

NO Match

Finally(){}

Page 24: Exception Handling - WordPress.com · Java Exception Handling • A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it

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

24