Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "duck an exception" mean?

In the Advantages of Exceptions section of the Java™ tutorials:

A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it.

[...]

...ducking an exception requires some effort on the part of the middleman methods. Any checked exceptions that can be thrown within a method must be specified in its throws clause.

What does "duck an exception" mean here? I searched the web and FOLDOC (Free On-line Dictionary of Computing) but didn't find anything that looked promising.

like image 355
user159 Avatar asked Nov 18 '15 08:11

user159


People also ask

What happens when you catch an exception?

The program resumes execution when the exception is caught somewhere by a "catch" block. Catching exceptions is explained later. You can throw any type of exception from your code, as long as your method signature declares it. You can also make up your own exceptions.

What does it mean for an exception to be thrown?

The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.


1 Answers

Well, ducking simply means to lower your head in order to avoid being hit or seen. In this case, 'duck an exception' just means avoiding your code from getting hit by an exception.

For your method not to be hit by exception, you throw it further up the call stack by declaring a throws exception on your method

public void myMethod() throws IOException {  } 

If you don't duck, you have to catch it:

public void myMethod() {     try {        // ...        } catch(IOException e) {       // handle exception     } 
like image 178
jmcg Avatar answered Oct 13 '22 07:10

jmcg