Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check for inner exception?

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?

like image 935
JL. Avatar asked Sep 21 '09 20:09

JL.


People also ask

How do I view inner exception in Visual Studio?

With a solution open in Visual Studio, use Debug > Windows > Exception Settings to open the Exception Settings window.

Can inner exception be null?

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.

Does exception ToString include inner exception?

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.

How do you throw an inner exception in Java?

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.)


2 Answers

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(); 
like image 82
jrista Avatar answered Oct 20 '22 09:10

jrista


Is this what you are looking for?

String innerMessage = (ex.InnerException != null)                        ? ex.InnerException.Message                       : ""; 
like image 34
Andrew Hare Avatar answered Oct 20 '22 07:10

Andrew Hare