Creating 2 Exceptions in a Finally Block - c#

I have the following code:
finally
{
if (!isDnsSet)
{
var exception = new Exception(<DNS-INFORMATION>);
localLog.TraceException(exception);
throw exception;
}
}
As it stands, this exception throws too much information to the user that is not particularly needed for them to see. I want to be able to log exception using my localLog class but also throw another exception with a more concise message.
I was thinking to just create another exception with the shortened message and still log the original, more verbose one using my class.
Is there a more elegant way of doing this or would I just do something like:
var shortException = new Exception(<short and sweet message>);
var longException = new Exception(<not so short and sweet but still useful for other devs>);
localLog.TraceException(longException);
throw shortException;

I think a cleaner method would be to make the longer exception an inner exception:
finally
{
if (!isDnsSet)
{
var innerException = new Exception(<not so short and sweet but still useful for other devs>);
var exception = new Exception(<short and sweet message>, innerException);
localLog.TraceException(exception);
throw exception;
}
}
That way you have consistency between the exception that's thrown and the exception that's logged, making diagnosis easier.

One approach is to create a custom exception that carries both a long and a short message. Users who get the exception outside your library would access the short message through Exception's Message property, while your TraceException method would access the long version through an additional property provided by your custom exception:
public class DetailedException : Exception {
public string DetailedMessage { get; }
public DetailedException(string longMessage, string shortMessage) : base(shortMessage) {
DetailedMessage = longMessage;
}
}
Inside TraceException method:
var message = (exception as DetailedException)?.DetailedMessage ?? exception.Message;

Couldn't the exception handler receive and process the longException and, as part of its function, throw the shortException?

Related

Where should I create an Exception object?

The Best practices for exceptions document on MSDN says that you can have an exception builder method inside your class if the same exception is to be used in many parts of the class. But also, it says that in some cases, it's better to use the exception's constructor.
Let's say I have the following code in an UserData class:
private MailAddress _addr;
public UserData(string emailAddress)
{
// Tries to validate the e-mail address
try
{
_addr = new MailAddress(emailAddress);
}
catch
{
throw new ArgumentException(nameof(emailAddress), "Invalid email address.");
}
if (_addr.Address != emailAddress)
{
throw new ArgumentException(nameof(emailAddress), "Invalid email address.");
}
}
You can see that in both throw statements, I'm throwing the exact same exception.
The question is: Is it correct to add an exception builder method to get my exception and throw that? Will I get the correct stacktrace and such if I do so? And if not, how do I determine between exception builders and constructors?
Is it correct to add an exception builder method to get my exception and throw that
That depends. As suggested in the article you linked: If it's the same exception (with the same information), it makes sense to create such a helper method to keep your code clean.
Will I get the correct stacktrace and such if I do so
Yes, you will.
Take a look at this example. (DotNetFiddle).
public static void Main()
{
try{
throw CreateEx("Hi");
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
try {
CreateEx2("Hi");
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
public static Exception CreateEx(string text){
text += " Additional text";
return new ArgumentOutOfRangeException(text);
}
public static void CreateEx2(string text){
text += " Additional text";
throw new ArgumentOutOfRangeException(text);
}
The stacktrace depends on where the exception is thrown, not where it is built.
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: Hi Additional text
at Program.Main() in d:\Windows\Temp\b4ln3dbq.0.cs:line 13
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: Hi Additional text
at Program.CreateEx2(String text) in d:\Windows\Temp\b4ln3dbq.0.cs:line 34
at Program.Main() in d:\Windows\Temp\b4ln3dbq.0.cs:line 19

Get name of last called method

I have the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
this.CheckValue(true); // call method
}
catch(Exception ex)
{
// how to get here name of last called method
}
}
public int CheckValue(bool sender)
{
var qwe = int.Parse("qwe"); // invoke an exception
return 0;
}
}
I need to get in "catch block" name of last called method (in this case "CheckValue"), but it return that called method is "StringToNumber".
I try to get it using StackTrace:
stackTrace.GetFrame(1).GetMethod().Name; -> "Main"
MethodBase.GetCurrentMethod(); -> "Void .ctor()"
ex.TargetSite.Name; -> "StringToNumber"
It's possible to do this?
Short Answer:
Yes, You can!!!
I'd just play around with Extension Methods and the trick here, is to get the last frame of the desired class, otherwise it would get methods of mscorlib assembly. So here it go:
public static string GetLastCalledMethod<T>(this Exception ex)
{
var stackTrace = new System.Diagnostics.StackTrace(ex);
var lastFrame = stackTrace.GetFrames().FirstOrDefault(frame => frame.GetMethod().DeclaringType.FullName == typeof(T).FullName);
string methodName = string.Empty;
if (lastFrame != null)
methodName = lastFrame.GetMethod().Name;
return methodName;
}
Short Answer:
You can't.
Long Answer:
If you really need to do that, you will need to perform logging code in all the methods you want to track.
You can create a global variable (ugh) to store a MethodInfo with the last called method, and inside every method, set it to MethodBase.GetCurrentMethod(). Then whenever you want, you can examine that variable to see which method set it last.
In your case, you probably are trying to determine which method the exception was thrown in. You are looking at TargetSite, which returns the lowest method in the hierarchy, whereas you seem to want the one immediately below the current method. If simply examining Exception.StackTrace doesn't provide enough information, you might be able to parse out information from StackTrace and use reflection to get a MethodInfo. Usually, the StackTrace is good enough.
You may also be able to throw a new exception in the top-level method, so you can get the TargetSite from the new one.
Summary:
If Exception.StackTrace doesn't provide enough information, then you will either have to:
Perform logging code in each method you want to check for.
Parse out what information you can get from the Exception.
Change the exception throwing scheme to throw a new exception with InnerException set to the original exception.
I don't know why you want to do this.. because this is expected behaviour. The site of the exception is what you're being shown.. within the int.Parse() calls.
That being said.. if you really want to do this, you need to wrap a try.. catch in CheckValue, and re-throw the exception from there, but in a way that breaks the call stack.. like so:
public int CheckValue(bool sender) {
try {
var qwe = int.Parse("qwe"); // invoke an exception
return 0;
}
catch (Exception ex) {
throw ex; // this breaks the call stack and re-throws the exception from here..
}
}
Then, ex.TargetSite.Name == "CheckValue". I'm still not sure why you'd want to do this.. as a stack trace will actually show you where it all unwinds from after failure.

How to catch the original (inner) exception in C#?

i'm calling a function that throws a custom exception:
GetLockOwnerInfo(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
And so on:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
ExecuteReaderClient(...)
Fill(...)
One of these functions throws an SqlException, although that code has no idea what an SqlException is.
Higher levels wrap that SqlException into another BusinessRuleException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (DbException ex)
{
BusinessRuleExcpetion e = new BusinessRuleException(ex)
...
throw e;
}
Higher levels wrap that BusinessRuleException into another LockerException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (BusinessRuleException ex)
{
LockerException e = new LockerException(ex)
...
throw e;
}
The problem now is that i want to catch the origianl SqlException, to check for a particular error code.
But there's no way to "catch the inner exception":
try
{
DoSomething();
}
catch (SqlException e)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
i thought about catching SqlException right when it's thrown, and copy various values to the re-thrown exception - but that code is not dependant on Sql. It is experiencing an SqlException, but it has no dependency on SqlException.
i thought about catching all exceptions:
try
{
DoSomething(...);
}
catch (Exception e)
{
SqlException ex = HuntAroundForAnSqlException(e);
if (ex != null)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
else
throw;
}
But that's horrible code.
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
You need c# 6 / visual studio 2015 in order to do this using a predicate:
catch (ArgumentException e) when (e.ParamName == “…”)
{
}
Official C# Try/Catch Documentation
I hate to have to tell you this, but you cannot catch an inner exception.
What you can do is inspect one.
I suggest you catch your high-level exception (I believe it was LockerException) and inspect the InnerException property of that exception. Check the type, and if it's not a SqlException, check the InnerException of that exception. Walk each one until you find a SqlException type, then get the data you need.
That said, I agree with dasblinkenlight that you should consider -- if possible -- a heavy refactor of your exception framework.
Checking the error code of a wrapped exception is not a good practice, because it hurts encapsulation rather severely. Imagine at some point rewriting the logic to read from a non-SQL source, say, a web service. It would throw something other than SQLException under the same condition, and your outer code would have no way to detect it.
You should add code to the block catching SQLException to check for e.Number = 247 right then and there, and throw BusinessRuleException with some property that differentiates it from BusinessRuleException thrown in response to non-SQLException and SQLException with e.Number != 247 in some meaningful way. For example, if the magic number 247 means you've encountered a duplicate (a pure speculation on my part at this point), you could do something like this:
catch (SQLException e) {
var toThrow = new BusinessRuleException(e);
if (e.Number == 247) {
toThrow.DuplicateDetected = true;
}
throw toThrow;
}
When you catch BusinessRuleException later, you can check its DuplicateDetected property, and act accordingly.
EDIT 1 (in response to the comment that the DB-reading code cannot check for SQLException)
You can also change your BusinessRuleException to check for SQLException in its constructor, like this:
public BusinessRuleException(Exception inner)
: base(inner) {
SetDuplicateDetectedFlag(inner);
}
public BusinessRuleException(string message, Exception inner)
: base(message, inner) {
SetDuplicateDetectedFlag(inner);
}
private void SetDuplicateDetectedFlag(Exception inner) {
var innerSql = inner as SqlException;
DuplicateDetected = innerSql != null && innerSql.Number == 247;
}
This is less desirable, because it breaks encapsulation, but at least it does it in a single place. If you need to examine other types of exceptions (e.g. because you've added a web service source), you could add it to the SetDuplicateDetectedFlag method, and everything would work again.
Having an outer application layer care about the details of a wrapped exception is a code smell; the deeper the wrapping, the bigger the smell. The class which you now have wrapping the SqlException into a dbException is presumably designed to expose an SqlClient as a generic database interface. As such, that class should include a means of distinguishing different exceptional conditions. It may, for example, define a dbTimeoutWaitingForLockException and decide to throw it when it catches an SqlException and determines based upon its error code that there was a lock timeout. In vb.net, it might be cleaner to have a dbException type which exposes an ErrorCause enumeration, so one could then say Catch Ex as dbException When ex.Cause = dbErrorCauses.LockTimeout, but unfortunately exception filters are not usable in C#.
If one has a situation where the inner-class wrapper won't know enough about what it's doing to know how it should map exceptions, it may be helpful to have the inner-class method accept an exception-wrapping delegate which would take an exception the inner class has caught or would "like" to throw, and wrap it in a way appropriate to the outer class. Such an approach would likely be overkill in cases where the inner class is called directly from the outer class, but can be useful if there are intermediate classes involved.
Good question and good answers!
I just want to supplement the answers already given with some further thoughts:
On one hand I agree with dasblinkenlight and the other users. If you catch one exception to rethrow an exception of a different type with the original exception set as the inner exception then you should do this for no other reason than to maintain the method's contract. (Accessing the SQL server is an implementation detail that the caller is not/must not/cannot be aware of, so it cannot anticipate that a SqlException (or DbException for that matter) will be thrown.)
Applying this technique however has some implications that one should be aware of:
You are concealing the root cause of the error. In your example you are reporting to the caller that a business rule was invalid(?), violated(?) etc., when in fact there was a problem accessing the DB (which would be immediately clear if the DbException were allowed to bubble up the call stack further).
You are concealing the location where the error originally occurred. The StackTrace property of the caught exception will point to a catch-block far away from the location the error originally occurred. This can make debugging notoriously difficult unless you take
great care to log the stack traces of all the inner exceptions as well. (This is especially true once the software has been deployed into production and you have no means to attach a
debugger...)
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
It is true that .NET does not allow you to alter the Message of an Exception. It provides another mechanism however to supply additional information to an Exception via the Exception.Data dictionary. So if all you want to do is add additional data to an exception, then there is no reason to wrap the original exception and throw a new one. Instead just do:
public void DoStuff(String filename)
{
try {
// Some file I/O here...
}
catch (IOException ex) {
// Add filename to the IOException
ex.Data.Add("Filename", filename);
// Send the exception along its way
throw;
}
}
As other peeps say, you cannot catch an the InnerException. A function such as this could help you get the InnerException out of the tree though:
public static bool TryFindInnerException<T>(Exception top, out T foundException) where T : Exception
{
if (top == null)
{
foundException = null;
return false;
}
Console.WriteLine(top.GetType());
if (typeof(T) == top.GetType())
{
foundException = (T)top;
return true;
}
return TryFindInnerException<T>(top.InnerException, out foundException);
}
I agree with the other comments that this is a code smell 🦨 and should be avoided. But if a refactor is not possible you could try something like this...
Create an extension method...
public static bool HasInnerException(this Exception ex, Func<Exception, bool> match)
{
if (ex.InnerException == null)
{
return false;
}
return match(ex.InnerException) || HasInnerException(ex.InnerException, match);
}
And use it like...
catch (Exception ex) when (ex.HasInnerException(e => e is MyExceptionThatIsHidden))
{
...
But really you should be solving for 👇
var exception = new Exception("wrapped exception 3",
new Exception("wrapped exception 2",
new Exception("wrapped exception 1",
new MyExceptionThatIsHidden("original exception")))); // <--- ???

a question about exception in c#

following is a code snippet:
class xxx
{
public xxx(){}
try
{
throw new Exception(InvalidoperationException);
}
catch(Exception x)
{
}
catch(InvalidoperationException x)
{
}
}
can anyone tell which exception will raise here and what is the reason behind it.
Wow, lots of problems here. Where to start?
That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.
Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.
Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.
You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.
Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.
I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:
class Xxx
{
public Xxx()
{
}
}
Not particularly helpful.
If the code is like this
class xxx
{
public xxx(){
try
{
throw new Exception(InvalidoperationException);
}
catch(InvalidoperationException x)
{
}
catch(Exception x)
{
}
}
}
It should compile and raise your exception and catch. Otherwise your code will not compile at all.
No exception will be thrown as this code will not even compile.
Regardless - several points:
When using exception handling, put the more specific exception before the less specific ones (so the catch of InvalidOperationException should be before the one for Exception).
Catching Exception is normally no very useful.
If you catch an exception, do something with it.
You probably meant:
throw new InvalidOperationException();
However, the way you structured your exceptions, the catch(Exception x) block would have run.
You should write:
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Do smth with exception;
}
catch(Exception exception)
{
throw; // Rethrows your exception;
}
}
}
InvalidOperationException inherits from Exception.
catch tries to processes the most specific branch, so catch (InvalidOperationException x) will be executed here.
Nope. It wouldn't compile. So, it there's no question about as to which exception will be generated.
Your code should be something like this :
class xxx
{
public void Test()
{
try
{
throw new InvalidoperationException();
}
catch(InvalidoperationException exception)
{
// Something about InvalidOperationException;
}
catch(Exception exception)
{
// Something about the Exception
}
}
}
Point to be noted :
Write more specific class of Exception first, hence we write InvalidOperationException prior to Exception class.
Ignoring the compile issue.... the first matching exception block (catch(Exception x)) will get the exception. You then ignore the exception and don't re-throw, so exception will be seen by the outside world. That doesn't make it good practice, though... in particular, catching an arbitrary Exception and ignoring it is risky - it could have been anything... it isn't necessarily the exception you thought it was.
Well, the code won't compile, but I'll just ignore that...
If I'll just look at the line:
throw new Exception(InvalidoperationException);
1st of all, according to MSDN there is no such constructor. So I will assume you meant the constructor: Exception(String msg, Exception innerException). Meaning:
throw new Exception("blabla", InvalidoperationException);
The exception that is being thrown is of type Exception and not InvalidOperationException. So ONLY catch(Exception x) can catch it.
If you would've thrown InvalidoperationException than the way you wrote the order of the catches, the Exception class would get caught first.
The order of the catches does matter.
The best advice I can give you is simply try it yourself and see what happens.

Programmatically suppressing exceptions in C#

I have the following try-catch statement and I do not want to not throw the exception if the message property contains 'My error' in the text.
How can I programmatcially accomplish this? Also, would this be considered code-smell?
try
{
}
catch(Exception e)
{
if(e.Messages.Contains("My error"))
{
//want to display a friendly message and suppress the exception
}
else
{
throw e;
}
}
You shouldn't catch errors based on the error test. You should make your own exception class that extends exception:
class MyErrorException : Exception { }
and throw and catch those. (Excuse my syntax if it's wrong, I haven't done C# in a while).
That being said, throwing and catching your own Exceptions instead of propagating them is perfectly normal, and it is how you actually should do exception handling.
You should be catching the specific exception you're looking for. Quite frankly, that code is shocking. You should have something like ...
public class MyCoolException : Exception {
public MyCoolException(string msg) : base(msg) {}
}
public void MyCoolMethod() {
// if bad things happen
throw new MyCoolException("You did something wrong!");
}
Then later in your code you can use it like ...
try {
MyCoolMethod();
} catch (MyCoolException e) {
// do some stuff
}
Your code creates maintainability issues because a simple text change can have strange side effects. You can have your own exception class which inherits from System.Exception. Then instead of having an if you could do the following:
try
{
}
catch(MyException myException) //or just catch(MyException)
{
//display a friendly message
}
also you don't want to do throw e because it doesn't preserver the Stack, just throw; will do.
When I throw Exception rather than a derived class I always mean a failed assertion. I don't like failing out the backend because we are still able to receive a request (just not that one again). If we're really toast it will just error out on the next request anyway.
When the back end needs to generate an error message I have a ErrorMessage class that inherits from Exception and takes ErrorMessage and ErrorMessageTitle as constructor arguments.

Categories