I know sometimes innerException is null
So the following might fail:
repEvent.InnerException = ex.InnerException.Message;
Is there a quick ternary way to check if innerException is null or not?
With a solution open in Visual Studio, use Debug > Windows > Exception Settings to open the Exception Settings window.
An object that describes the error that caused the current exception. The InnerException property returns the same value as was passed into the Exception(String, Exception) constructor, or null if the inner exception value was not supplied to the constructor.
If you want information about all exceptions then use exception. ToString() . It will collect data from all inner exceptions. If you want only the original exception then use exception.
Absolutely - you can retrieve the inner exception (the "cause") using Throwable. getCause() . To create an exception with a cause, simply pass it into the constructor. (Most exceptions have a constructor accepting a cause, where it makes sense.)
Great answers so far. On a similar, but different note, sometimes there is more than one level of nested exceptions. If you want to get the root exception that was originally thrown, no matter how deep, you might try this:
public static class ExceptionExtensions { public static Exception GetOriginalException(this Exception ex) { if (ex.InnerException == null) return ex; return ex.InnerException.GetOriginalException(); } }
And in use:
repEvent.InnerException = ex.GetOriginalException();
Is this what you are looking for?
String innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With