Re: Why does Java require the throws clause? Good or bad language
design?
Arthur J. O'Dwyer wrote:
In C++, we can write
....
How would the same thing be written in Java? Notice that the
function 'higherLevel' does not know (or need to know) anything
about the exception specification of 'callbackFunc'; I claim that
this is good design, because it means that 'higherLevel' can be
reused in other contexts.
The "contract" here is between 'catcher' and 'callbackFunc';
No, there isn't any contract between these two.
catcher calls higherLevel, so one contract is between catcher and
higherLevel.
higherLevel calls cbf, so there's another contract: between higherLevel
and cbf.
Now, let's reformulate your code in Java:
interface CBF {
public void execute(int x);
}
public void higherLevel( CBF cbf, int arr[] ) {
for ( int i = 0; i < arr.length; i++ )
cbf.execute(arr[i]);
}
public void catcher() {
int arr[] = new int[]{1,2,3,42,5};
higherLevel( callBackFunc, arr );
}
There are two things to mention:
1. callBackFunc is not defined, yet.
2. If one looks at CBF one can see the obvious contract that must be
fullfilled when calling or *implementing* CBF#execute:
- the caller must provide one argument of type int.
- execute does not throw a checked exception.
Now, let's implement CBF:
CBF callBankFunc = new CBF() {
public void execute( int x ) {
if ( x == 42 )
throw new Exception();
}
};
This would lead to a compile-time error since the CBF promises that
there's no checked exception when 'execute' gets called.
If you really want to throw an exception, there are two ways. Either
throw an unchecked exception or if you a checked exception should be
thrown, declare it in CBF#execute's throws-clause.
E.g. throw new IllegalArgumentException("Invalid: 42");
Bye
Michael