You can do it, but you shouldn't1.
I assume that you are talking about the athrow
bytecode instruction. (And that you really asking if you can trigger an exception from your code without using a throw
statement.)
There are (at least) two ways for an application to throw an arbitrary Java exception (checked or unchecked) that don't involve an explicit athrow
instruction.
You can call Unsafe.throwException(Throwable)
.
In native code, you can call the Throw
or ThrowNew
functions in the JNI API.
In both cases, you can circumvent the Java (compile time and verifier) checks that are intended to ensure that checked exceptions are always declared (via a throws
clause) or handled.
Note using Unsafe
or native code means that your code is not Pure Java. It won't be portable. Furthermore it is easy to do things that will make a JVM unstable. JVM crashes are not unusual.
In addition, the JVM will itself throw exceptions without an athrow
instruction. For example, if you try to use new FileInputStream
to open a file that doesn't exist and FileNotFoundException
is thrown, it is being throw from native code, not from compiled Java code.
It follows that your application can use this mechanism to implicitly throw many checked and unchecked exceptions; e.g. by deliberately trying to open a non-existent file. However, the method signature for read
declares that it may throw IOException
, so the compiler knows about this ... from the perspective of the checked exception rules.
1 - And if you application design requires this kind of craziness, you would be advised to come up with an alternative. It is a bad idea to try to fight Java's checked exception rules. If you dislike them so much that you are contemplating this, you should pick a different programming language.