2015-09-07 11:44:36 -06:00
|
|
|
// exceptions/TurnOffChecking.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// "Turning off" Checked exceptions
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.io.*;
|
|
|
|
|
|
|
|
class WrapCheckedException {
|
|
|
|
void throwRuntimeException(int type) {
|
|
|
|
try {
|
|
|
|
switch(type) {
|
|
|
|
case 0: throw new FileNotFoundException();
|
|
|
|
case 1: throw new IOException();
|
2017-05-10 11:45:39 -06:00
|
|
|
case 2: throw new
|
|
|
|
RuntimeException("Where am I?");
|
2015-06-15 17:47:35 -07:00
|
|
|
default: return;
|
|
|
|
}
|
|
|
|
} catch(IOException | RuntimeException e) {
|
|
|
|
// Adapt to unchecked:
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class SomeOtherException extends Exception {}
|
|
|
|
|
|
|
|
public class TurnOffChecking {
|
|
|
|
public static void main(String[] args) {
|
2017-05-10 11:45:39 -06:00
|
|
|
WrapCheckedException wce =
|
|
|
|
new WrapCheckedException();
|
|
|
|
// You can call throwRuntimeException() without
|
|
|
|
// a try block, and let RuntimeExceptions
|
|
|
|
// leave the method:
|
2015-06-15 17:47:35 -07:00
|
|
|
wce.throwRuntimeException(3);
|
|
|
|
// Or you can choose to catch exceptions:
|
|
|
|
for(int i = 0; i < 4; i++)
|
|
|
|
try {
|
|
|
|
if(i < 3)
|
|
|
|
wce.throwRuntimeException(i);
|
|
|
|
else
|
|
|
|
throw new SomeOtherException();
|
|
|
|
} catch(SomeOtherException e) {
|
2017-05-10 11:45:39 -06:00
|
|
|
System.out.println(
|
|
|
|
"SomeOtherException: " + e);
|
2015-06-15 17:47:35 -07:00
|
|
|
} catch(RuntimeException re) {
|
|
|
|
try {
|
|
|
|
throw re.getCause();
|
|
|
|
} catch(FileNotFoundException e) {
|
2016-01-25 18:05:55 -08:00
|
|
|
System.out.println(
|
|
|
|
"FileNotFoundException: " + e);
|
2015-06-15 17:47:35 -07:00
|
|
|
} catch(IOException e) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("IOException: " + e);
|
2015-06-15 17:47:35 -07:00
|
|
|
} catch(Throwable e) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Throwable: " + e);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
FileNotFoundException: java.io.FileNotFoundException
|
|
|
|
IOException: java.io.IOException
|
|
|
|
Throwable: java.lang.RuntimeException: Where am I?
|
|
|
|
SomeOtherException: SomeOtherException
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|