Skip to main content

An extension to "throws" clause in method signatures

3 replies [Last post]
roozbeh
Offline
Joined: 2003-06-13

The complete description is in http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6534270
The idea is to support a new keyword in method signatures: "suppresses". I just provide a couple of examples:

void doSomeWork() suppresses IOException
{
____RandomAccessFile raf = ...;
____raf.write(...);
____raf.close();
}

would be equivalent to

void doSomeWork()
{
____try {
________RandomAccessFile raf = ...;
________raf.write(...);
________raf.close();
____} catch (IOException e) {
________throw new RuntimeException(e);
____}
}

Also

int getCount() suppresses IOException, MyAlgorithmException
________throws MyException
{
____int x = raf.length(); // RandomAccessFile.length()
____return myAlgorithm(x);
}

is equivalent to

int getCount() throws MyException
{
____try {
________int x = raf.length();
________return myAlgorithm(x);
____} catch (IOException e) {
________throw new RuntimeException(e);
____} catch (MyAlgorithmException e) {
________throw new RuntimeException(e);
____}
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
roozbeh
Offline
Joined: 2003-06-13

I was trying to keep the example as simple as possible just to demonstrate the idea. As adiguba showed, you can still follow good coding practices such as releasing the resources in a finally block.

sjasja
Offline
Joined: 2004-08-15

The first example (probably the second one too) shows one problem: it makes it even easier to have resource leaks. In this case doing raf.close() in a finally statement. I find most checked exceptions are IOExceptions and SQLExceptions, most of which would be associated with a resource leak.

adiguba
Offline
Joined: 2005-07-12

> The first example (probably the second one too) shows
> one problem: it makes it even easier to have resource
> leaks. In this case doing raf.close() in a finally
> statement.

You can use a try/finally bloc to call close() :

[i]void doSomeWork() suppresses IOException
{
____RandomAccessFile raf = ...;
____try {
________raf.write(...);
____} finally {
________raf.close();
____}
}[/i]

would be equivalent to

[i]void doSomeWork()
{
____try {
________RandomAccessFile raf = ...;
________try {
____________raf.write(...);
________} finally {
____________raf.close();
________}
____} catch (IOException e) {
________throw new RuntimeException(e);
____}
}
[/i]