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.

}<br />

It is often convenient to <strong>in</strong>stantiate an exception object at the time the exception has<br />

to be thrown. Thus, a throw statement is typically written as follows:<br />

throw new exception_type(param 0 , param 1 , …, param n−1 );<br />

where exception_type is the type of the exception <strong>and</strong> the param i 's form the list of<br />

parameters for a constructor for this exception.<br />

Exceptions are also thrown by the <strong>Java</strong> run-time environment itself. For example,<br />

the counterpart to the example above is<br />

ArrayIndexOutOfBoundsException. If we have a six-element array <strong>and</strong><br />

ask for the n<strong>in</strong>th element, then this exception will be thrown by the <strong>Java</strong> run-time<br />

system.<br />

The Throws Clause<br />

When a method is declared, it is appropriate to specify the exceptions it might<br />

throw. This convention has both a functional <strong>and</strong> courteous purpose. For one, it<br />

lets users know what to expect. It also lets the <strong>Java</strong> compiler know which<br />

exceptions to prepare for. The follow<strong>in</strong>g is an example of such a method<br />

def<strong>in</strong>ition:<br />

public void goShopp<strong>in</strong>g() throws<br />

Shopp<strong>in</strong>gListTooSmallException,<br />

}<br />

// method body…<br />

OutOfMoneyException {<br />

By specify<strong>in</strong>g all the exceptions that might be thrown by a method, we prepare<br />

others to be able to h<strong>and</strong>le all of the exceptional cases that might arise from us<strong>in</strong>g<br />

this method. Another benefit of declar<strong>in</strong>g exceptions is that we do not need to<br />

catch those exceptions <strong>in</strong> our method. Sometimes this is appropriate <strong>in</strong> the case<br />

where other code is responsible for caus<strong>in</strong>g the circumstances lead<strong>in</strong>g up to the<br />

exception.<br />

The follow<strong>in</strong>g illustrates an exception that is "passed through":<br />

public void getReadyForClass() throws<br />

Shopp<strong>in</strong>gListTooSmallException,<br />

OutOfMoneyException {<br />

112

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

Saved successfully!

Ooh no, something went wrong!