Exceptions/Catch an exception thrown in a nested call: Difference between revisions

added java
(Ada)
(added java)
Line 47:
Procedure Foo caught exception U0
Exception U1 passed through foo</pre>
 
=={{header|Java}}==
Methods that may throw an exception (or that call a method that may throw an exception that it does not catch) must explicitly declare that they can throw such an exception (or a superclass thereof), unless they are unchecked exceptions (subclasses of <code>RuntimeException</code> or <code>Error</code>):
<lang java>class U0 extends Exception { }
class U1 extends Exception { }
 
public class ExceptionsTest {
public static void foo() throws U1 {
for (int i = 0; i <= 1; i++) {
try {
bar(i);
} catch (U0 e) {
System.out.println("Function foo caught exception U0");
}
}
}
 
public static void bar(int i) throws U0, U1 {
baz(i); // Nest those calls
}
 
public static void baz(int i) throws U0, U1 {
if (i == 0)
throw new U0();
else
throw new U1();
}
 
public static void main(String[] args) throws U1 {
foo();
}
}</lang>
Sample output:
<pre>
Function foo caught exception U0
Exception in thread "main" U1
at ExceptionsTest.baz(ExceptionsTest.java:23)
at ExceptionsTest.bar(ExceptionsTest.java:16)
at ExceptionsTest.foo(ExceptionsTest.java:8)
at ExceptionsTest.main(ExceptionsTest.java:27)
</pre>
The first line of the output is generated from catching the U0 exception in function foo.
 
Uncaught exceptions give information showing where the exception originated through the nested function calls together with the name of the uncaught exception, (U1) to stderr, then quit the running program.
 
=={{header|OCaml}}==
Anonymous user