Exceptions in Java

Exceptions in Java - Exceptions in Java What is an...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
Exceptions in Java
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates error handling from main business logic Based on ideas developed in Ada, Eiffel and C++ Java has a uniform approach for handling all synchronous errors From very unusual (e.g. out of memory) To more common ones your program should check itself (e.g. index out of bounds) From Java run-time system errors (e.g., divide by zero) To errors that programmers detect and raise deliberately
Background image of page 2
Throwing and catching An error can throw an exception throw <exception object>; By default, exceptions result in the thread terminating after printing an error message However, exception handlers can catch specified exceptions and recover from error catch (<exception type> e) { //statements that handle the exception
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Throwing an exception Example creates a subclass of Exception and throws an exception: class MyException extends Exception { } class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ } else { /* error occurred */ throw new MyException(); } } //oops }//class MyClass
Background image of page 4
Exceptional flow of control Exceptions break the normal flow of control. When an exception occurs, the statement that would normally execute next is not executed. What happens instead depends on: whether the exception is caught, where it is caught, what statements are executed in the ‘catch block’, and whether you have a ‘finally block’.
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Approaches to handling an exception 1. Prevent the exception from happening 2. Catch it in the method in which it occurs, and either a. Fix up the problem and resume normal execution
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 08/06/2008 for the course CSE 432 taught by Professor Blank during the Fall '08 term at Lehigh University .

Page1 / 17

Exceptions in Java - Exceptions in Java What is an...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online