23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

2.3 Exceptions<br />

Exceptions are unexpected events that occur dur<strong>in</strong>g the execution of a program. An<br />

exception can be the result of an error condition or simply an unanticipated <strong>in</strong>put. In<br />

any case, <strong>in</strong> an object-oriented language, such as <strong>Java</strong>, exceptions can be thought of<br />

as be<strong>in</strong>g objects themselves.<br />

2.3.1 Throw<strong>in</strong>g Exceptions<br />

In <strong>Java</strong>, exceptions are objects that are thrown by code that encounters some sort of<br />

unexpected condition. They can also be thrown by the <strong>Java</strong> run-time environment<br />

should it encounter an unexpected condition, like runn<strong>in</strong>g out of object memory. A<br />

thrown exception is caught by other code that "h<strong>and</strong>les" the exception somehow, or<br />

the program is term<strong>in</strong>ated unexpectedly. (We will say more about catch<strong>in</strong>g<br />

exceptions shortly.)<br />

Exceptions orig<strong>in</strong>ate when a piece of <strong>Java</strong> code f<strong>in</strong>ds some sort of problem dur<strong>in</strong>g<br />

execution <strong>and</strong> throws an exception object. It is convenient to give a descriptive<br />

name to the class of the exception object. For <strong>in</strong>stance, if we try to delete the tenth<br />

element from a sequence that has only five elements, the code may throw a<br />

BoundaryViolationException. This action could be done, for example,<br />

us<strong>in</strong>g the follow<strong>in</strong>g code fragment:<br />

if (<strong>in</strong>sertIndex >= A.length) {<br />

throw new<br />

BoundaryViolationException("No element at <strong>in</strong>dex " +<br />

<strong>in</strong>sertIndex);<br />

111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!