Lesson 11: Handling Exceptions
Introduction
In general, Java exceptions are translated into .NET proxy exceptions that can be caught and used just like regular .NET exceptions. When a Java operation throws an exception, the JuggerNET managed runtime catches it and translates it into the best-matching .NET exception. The concept of "best-matching" is important because you never know for sure what kind of Java exception might get thrown and you will almost certainly not have proxy types for all possible Java exception types available!
The JuggerNET runtime is pretty smart about exceptions. When it catches a Java exception during the execution of a JNI
command on behalf of a proxy type, it will first check to see whether the exact proxy type is available. If the answer is
yes, it will create an instance of that type and throw it. If the answer is no, it will check whether the exception's
supertype is available as a proxy type. If yes, it will create an instance of that type and throw it; if not, it will
continue up the inheritance chain of exception types until it has analyzed all of them and not found a matching proxy type.
In this case, it will end up throwing a Codemesh.JuggerNET.JuggerNETProxyException
, which represents a generic
proxy exception type.
There is one more kind of exception that can be thrown by the managed runtime: the Codemesh.JuggerNET.JuggerNETFrameworkException
.
This exception type is used to signal problems at the framework level, problems which do not have a corresponding Java
root cause. The most basic of such problems is of course the overall inability to load a JVM. As a general rule, your
application should have a well-defined JVM initialization block and catch the JuggerNETFrameworkException
type
to handle misconfiguration-based errors that are most likely to occur at JVM initialization time (see Configuration).
When you're handling .NET exceptions, you can gain access to the complete stacktrace via the StackTrace
property
and to the exception's message via the Message
property.
Unexpected Differences
In .NET, all types that can be used as exceptions need to extend the System.Exception
type. This
means that our proxy exception types cannot extend the proxy type for java.lang.Object
because .NET
(like Java) only allows one superclass per type.
Consequently, proxy Exception
instances are not proxy Object
instances and you
cannot directly use a proxy Exception
instance in a place that expects a proxy Object
.
This is typically not a serious limitation and can be worked around using the From()
cast that is explained
in the previous lesson.