.NET Exceptions: Does each exception type have its own message text? - exception

We use ELMAH for our ASP.NET web app and I am stumped as to some of the exceptions we get. Some of these are:
System.FormatException: Invalid length for a Base-64 char array.
System.Web.HttpException: Unable to validate data.
System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.
I simply have no idea why they occur, but the end user apparently does not see them, so I want to ignore them and supress the emails. If I do this, I want to make sure that System.FormatException only uses Invalid length for a Base-64 char array. for its message text and not also some other message. If it did and I ignored it, I might be missing out on other exceptions that are thrown under System.FormatException. If that is the case, I'd have to check for the message text. That's not a problem, but I really don't like hardcoding strings in my app.
Update:
I tried this code:
try
{
throw new System.FormatException();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.Read();
And its message text is:
One of the identified items was in an invalid format.
This tells that the answerer is right and that exceptions should be ignored based on both exception and message text.

The exception's Message property is not useful to help you diagnose bugs in your code or problems with the user's configuration. This is also why you don't know why they occur. You must put more information in your email, particularly the exception's StackTrace property is crucial to help you find out exactly where the exception occurred. If an exception has an InnerException then you always need to know that one as well since it is typically the core reason another exception got triggered.
Simply use the exception's ToString() method to generate a better diagnostic to put in your email message.

Related

AS3, Flash: Accessing error messages text in code

I'm working on some flash app. Now, to test customer side of it I can use Flash Player debugger version that will save logs and show error messages. When it's deployed on the customer side - they will have a regular Flash Player version which means I will have no access to error messages if errors will happen. So I would like to equip it with some tool that would capture all of my trace messages in code and errors text. As for trace messages that's fairly simple, I just override the function in my code so it sends a POST request with trace message to a logger server, but how can I get a hold of the error message? Is there a known approach to this or some trick that somebody can suggest?
You can install the debug version of flash as your browser's default (in Chrome, you must disable the built-in player), so if you wanted to test user experience and debug, this would be the ideal solution.
However, to answer your question: there's no method for universally catching all errors, and redirecting them (that I know of). You'd have to encapsulate problem code ahead of time with try...catch statements, and send the property back on catch. For example:
try {
this["foo"]();
} catch (e:Error) {
trace(e);
}
In the debug version, the traced value would be TypeError: Error #1006: value is not a function. And while the standard version will only output TypeError: Error #1006, (a notably less descriptive error), what we're missing is any reference to where the error occured. To get this, we need to use Error.getStackTrace() to see the call stack and the line where the error occurred. In debug, this outputs the following:
TypeError: Error #1006: value is not a function.
at Shell_fla::MainTimeline/init()[C:\Projects\shell.as:91
In the standard client, we get a dissapointing null. In short, you cannot get any valuable info from the client versions.
The best advice I can give is to write around your problem code with your own custom error reports. For example, catch IO errors and trace the file it failed to load, or if you're expecting an object.foo, first try if (object.hasOwnProperty("foo")) { // do something } else { trace("foo not found in " + object.name) }. Code defensively.
Cheers,
I've discovered this post on StackOverflow:
How to catch all exceptions in Flex?
It answers my question, strange that I haven't ran into it while I was googling prior to asking.

cfthrow is this how you use it? (from Adobe's doc)

I was reading the documentation for cfthrow and came accross this
When to use the cfthrow tag
Use the cfthrow tag when your application can identify and handle
application-specific errors. One typical use for the cfthrow tag is in
implementing custom data validation. The cfthrow tag is also useful
for throwing errors from a custom tag page to the calling page.
For example, on a form action page or custom tag used to set a
password, the application can determine whether the password entered
is a minimum length, or contains both letters and number, and throw an
error with a message that indicates the password rule that was broken.
The cfcatch block handles the error and tells the user how to correct
the problem.
Have I been doing it wrong all this time or is this just a terrible use-case?
I was taught that exceptions shouldn't be used to handle regular application flow but for stuff that is somewhat out of your control. For example, a file being locked when you go to write to it.
A user breaking a password rule doesn't quite sound like something that's out of your control.
That is a poor example not a poor use case. I personally would pass in the parameters to a validation function and return a result that contained a pass or fail and a collection of failure messages to display to the user.
How I use exceptions is as follows.
Within functions. Let's say that you have a function that you are getting some data from the database and you are then constructing a structure from it. If the query returned has no values you have several options:-
You could return an empty structure and let the calling code deduce the problem from the fact the structure is empty. This is not ideal because then the application has to have complicated logic to address the missing data.
You could return a more complex datatype where one property is whether the process went ok and the actual data. Again this is not optimal as you have to then make this access the property on every call when the majority of the time you have data and again your application is dealing with this issue.
Or you could raise a custom exception with cfthrow indicating that there is no record that matches. This then means that you can choose to ignore the prospect of this error happening and let it bubble up to the onError handler or you could surround it in a try catch statement and deal with it there and then. This keeps your API clean and sensible.
Wrapping external errors let's say that you connect to an external API using cfhttp over https. Now this requires installing the certificate in your keystore otherwise it throws an error. If this certificate gets updated then it will start erroring again. In this instance I would wrap the call in a try catch and should this be the error I would wrap that in my own custom exception with a message detailing that we need to update the cert in the keystore so that any developer debugging it knows what to do to fix it without having to work it out. If it is not that particular error then I would cfrethrow it so that it bubbles up and is dealt with by whatever exception handling logic is above the call.
These are just a few examples, but there are more. To summarise I would say that throwing exceptions is a way of communicating up through the tiers of an application when something has occurred that is not the hoped for behaviour while keeping your API/Application logic clean and understandable.
It's really up to your discretion. It's extremely common in many languages to use exceptions for everything, including input validation.
Importantly, exceptions have nothing to do with something being in your control or not. For example, suppose that you have a fairly long and complicated module that uploads a file. There are many fail points in something like that: the file could be too big, the file could be the wrong format, etc. Without exceptions your only option is a lot of if/then checks and some kind of status return at the very end. With exceptions, all you have to do is use a set of cfthrows:
<cfthrow type="FileUpload.TooBig" message="The file size was #FileSize#, but the maximum size allowed is #MaxFileSize#">
<cfthrow type="FileUpload.WrongType" message="The file type was #FilType#, but the accepted types are #AcceptedTypeList#">
Then, whatever is calling the file upload function can catch either with <cfcatch type="FileUpload"> or catch a specific one (e.g. <cfcatch type="FileUpload.WrongType">).
Also, technically a user breaking a password is out of your control, in the sense that the user has determined the value for the password. That said, I loathe password rules as invariably they make it harder, not easier, to maintain security.

Method design decision; when to throw an exception?

Suppose I have a method that must return an object (say from a database layer) and takes as input some info about the requested object.
In the normal case, the method should return the object. But what happens if the precondition of the methods are not fulfilled by the caller; how should I (the code writer of the method) inform the caller?
Take for example the case that I should return information about the user from a db, and I take as input the username and the password. In the normal case I should return the User object. But what if the username and password are null, if they mismatch, if the password is too short... how should I inform the caller what is exactly the problem?
Normally I would have thrown an exception, but here - When to throw an exception? was suggested that it is a bad idea.
Should I put an errorDetail field in the User, or make a method checkInputData or getErrorStatus...
It sounds perfectly reasonable to throw an exception in this case. The method, which should be doing one thing and only one thing, is simply trying to fetch a user record from the database. If a precondition fails, give up. If the database errors out, give up. If no user is found, give up. Let the calling code deal with the consequences.
An exception is a perfectly acceptable exit path for a method.
In the case of the precondition, it's not the method's responsibility to fix that. It's the calling code's responsibility. So throw an ArgumentException of some kind and let the calling code deal with it.
In the case of a database error, either catch it and throw a custom exception (something like an InfrastructureFailed exception) for the application to handle accordingly. Basically the application needs to tell the user that there are technical difficulties and to please try again later.
In the case of no user being found, that sounds like a failed login. Throw some kind of SecurityException and let the calling application handle it by notifying the user that the login has failed. (Don't be more specific. For example, don't tell the user that the username was fine but the password was bad. That's giving a malicious user more information than you want them to have. Just say that the login failed, nothing more.)
You also mention a case of a password being too short. I imagine that's something that should be validated before it gets to this point. In this case, that falls up under input checking for the method. So the preconditions fail and the method never even tries to get to the database. But "password is too short" probably isn't a good error to tell a user at a login prompt. Rather, that's for when they try to create the password.
One thing you shouldn't do is return null or an empty user object or anything like that. This puts the onus on the calling code to check if there was an error. Exceptions are a perfectly valid way of notifying calling code of an error. A "magic object" being returned is just like any other "magic string" in code, but worse because it leaks out of the method and into other code.
Now, this isn't always a complete rule, of course. It depends on the structure of the application. For example, if this is a web service or some other kind of request/response system then you might want to have a standard response object which would indicate failure. That assumes some application context around the method, though. And in that case you probably should still be dealing with multiple methods. The inner one (a domain logic method) would throw the exception, the outer one (an application UX-aware method) would catch the exception and craft an appropriate non-null response to the UI.
How you handle the exception is up to the logical structure of your application. But throwing and catching exceptions (keep in mind that "catching" is not the same thing as meaningfully "handling") is perfectly acceptable behavior.
Does it make sense to return some kind of sentinel value? If so, consider using that. Otherwise, why not throw an exception?
I would return an object that contains both a user (null in the case of an error), a success flag (false in the case of an error) and a list of strings as validation messages (on error, a list of reasons why it failed).
Adding an errorDetail field on the user object doesn't make sense since that is not really a property of the user object. It's just part of this return data from the method. This path leads to objects with muddles properties that are only used by certain methods.

BizTalk 2006 R2 schema validation specific error message with failed message routing

I'm looking for a way to catch the actual exception thrown by BizTalk 2006 R2 when a receive port can't parse a message it picks up.
For example, I have a csv file that was not properly created, say it's missing a comma, so when BizTalk tries to determine the message type, it errors out. Without using failed message routing, there are 2 entries in the application event log. One has a pretty generic error description, something along the lines of "The Messaging Engine encountered an error during the processing of one or more inbound messages." The second entry has what I'm looking for. It will contain the details of where the missing comma is, something along the lines of "Unexpected data found while looking for:
','
The current definition being parsed is POSTrailer. The stream offset where the error occured is 44443. The line number where the error occured is 244. The column where the error occured is 1."
I've tried using the ESB toolkit Exception Handler for BizTalk 2006 R2. Using failed message routing and their exception handing framework, the error description it catches is the first, generic, error description.
I do not see any way to obtain the second, more detailed error description. I'm assuming somewhere in the bowels of the biztalk messaging engine this exception is getting thrown, which is caught by something a little bit higher in the process, which throws it's own generic biztalk exception. I would also assume that the more specific error description is contained as the inner exception of the exception that gets routed to the ESB toolkit, however by the time I can get a hold of it, as far as I can tell, the actual exception object has been replaced by the message context, which is nothing more than a bunch of name/value pairs. The error description is now the generic one that is not helpful, and anything resembling an inner exception is just a hexidecmal code, which means nothing to my end users.
Everything I've found regarding obtaining a specific error message deals with exceptions thrown from an orchestration. I am not dealing with an orchestration, though, I'm dealing with a receive port. The closest thing I can find is here. But even if I could create a custom pipeline component using that, that means I either need to add that component into every exising custom pipline, or create a new one to validate XML and use that instead of the XMLRecieve or XMLSend pipelines that come with BizTalk... That also means trapping errors generated from EDI is out of the question. Does anyone know of a way to get at this more detailed error description from the BizTalk generated error message?
I'm not sure of a tool that will do exactly what you're looking for, but I do have a couple of options.
1) I'm pretty sure SCOM can grab those errors and alert whoever needs to be alerted. I've had some problems with this in the past, though, so it may not be your best bet.
2) For basic Failure handling, you can write code to scrape the EventLog for any warning or error from BizTalk and pass that down the line (my current client does this- it's not super elegant, but it works well).
3) What I would encourage- if you don't want orchestrations- is to set up custom pipelines which simply implement your error handling/monitoring in addition to your normal operations. Then, for non-critical messages, you can still use the standard pipelines (reducing overhead/latency) and for critical messages you can use your "GuaranteedDeliveryPassThruPipeline" or your "GuaranteedDeliveryXMLTransmitPipeline" or whatever.

Why are empty catch blocks a bad idea? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've just seen a question on try-catch, which people (including Jon Skeet) say empty catch blocks are a really bad idea? Why this? Is there no situation where an empty catch is not a wrong design decision?
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.
It's the programming equivalent of putting black tape over an engine warning light.
I believe that how you deal with exceptions depends on what layer of the software you are working in: Exceptions in the Rainforest.
They're a bad idea in general because it's a truly rare condition where a failure (exceptional condition, more generically) is properly met with NO response whatsoever. On top of that, empty catch blocks are a common tool used by people who use the exception engine for error checking that they should be doing preemptively.
To say that it's always bad is untrue...that's true of very little. There can be circumstances where either you don't care that there was an error or that the presence of the error somehow indicates that you can't do anything about it anyway (for example, when writing a previous error to a text log file and you get an IOException, meaning that you couldn't write out the new error anyway).
I wouldn't stretch things as far as to say that who uses empty catch blocks is a bad programmer and doesn't know what he is doing...
I use empty catch blocks if necessary. Sometimes programmer of library I'm consuming doesn't know what he is doing and throws exceptions even in situations when nobody needs it.
For example, consider some http server library, I couldn't care less if server throws exception because client has disconnected and index.html couldn't be sent.
Exceptions should only be thrown if there is truly an exception - something happening beyond the norm. An empty catch block basically says "something bad is happening, but I just don't care". This is a bad idea.
If you don't want to handle the exception, let it propagate upwards until it reaches some code that can handle it. If nothing can handle the exception, it should take the application down.
I think it's okay if you catch a particular exception type of which you know it's only going to be raised for one particular reason, and you expect that exception and really don't need to do anything about it.
But even in that case, a debug message might be in order.
There are rare instances where it can be justified. In Python you often see this kind of construction:
try:
result = foo()
except ValueError:
result = None
So it might be OK (depending on your application) to do:
result = bar()
if result == None:
try:
result = foo()
except ValueError:
pass # Python pass is equivalent to { } in curly-brace languages
# Now result == None if bar() returned None *and* foo() failed
In a recent .NET project, I had to write code to enumerate plugin DLLs to find classes that implement a certain interface. The relevant bit of code (in VB.NET, sorry) is:
For Each dllFile As String In dllFiles
Try
' Try to load the DLL as a .NET Assembly
Dim dll As Assembly = Assembly.LoadFile(dllFile)
' Loop through the classes in the DLL
For Each cls As Type In dll.GetExportedTypes()
' Does this class implement the interface?
If interfaceType.IsAssignableFrom(cls) Then
' ... more code here ...
End If
Next
Catch ex As Exception
' Unable to load the Assembly or enumerate types -- just ignore
End Try
Next
Although even in this case, I'd admit that logging the failure somewhere would probably be an improvement.
Per Josh Bloch - Item 65: Don't ignore Exceptions of Effective Java:
An empty catch block defeats the purpose of exceptions
At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Empty catch blocks are usually put in because the coder doesn't really know what they are doing. At my organization, an empty catch block must include a comment as to why doing nothing with the exception is a good idea.
On a related note, most people don't know that a try{} block can be followed with either a catch{} or a finally{}, only one is required.
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's On Error Resume Next, except that anything in the try block after the exception is thrown will be skipped.
Which doesn't help when something then breaks.
This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.
Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up and being handled correctly by another try block. Always try and do something with the exception you are catching.
I think a completely empty catch block is a bad idea because there is no way to infer that ignoring the exception was the intended behavior of the code. It is not necessarily bad to swallow an exception and return false or null or some other value in some cases. The .net framework has many "try" methods that behave this way. As a rule of thumb if you swallow an exception, add a comment and a log statement if the application supports logging.
If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.
try
{
string a = "125";
int b = int.Parse(a);
}
catch (Exception ex)
{
Log.LogError(ex);
}
Because if an exception is thrown you won't ever see it - failing silently is the worst possible option - you'll get erroneous behavior and no idea to look where it's happening. At least put a log message there! Even if it's something that 'can never happen'!
I find the most annoying with empty catch statements is when some other programmer did it. What I mean is when you need to debug code from somebody else any empty catch statements makes such an undertaking more difficult then it need to be. IMHO catch statements should always show some kind of error message - even if the error is not handled it should at least detect it (alt. on only in debug mode)
It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.
try
{
// Do some processing.
}
catch (FileNotFound fnf)
{
HandleFileNotFound(fnf);
}
catch (Exception e)
{
if (!IsGenericButExpected(e))
throw;
}
public bool IsGenericButExpected(Exception exception)
{
var expected = false;
if (exception.Message == "some expected message")
{
// Handle gracefully ... ie. log or something.
expected = true;
}
return expected;
}
Generally, you should only catch the exceptions you can actually handle. That means be as specific as possible when catching exceptions. Catching all exceptions is rarely a good idea and ignoring all exceptions is almost always a very bad idea.
I can only think of a few instances where an empty catch block has some meaningful purpose. If whatever specific exception, you are catching is "handled" by just reattempting the action there would be no need to do anything in the catch block. However, it would still be a good idea to log the fact that the exception occurred.
Another example: CLR 2.0 changed the way unhandled exceptions on the finalizer thread are treated. Prior to 2.0 the process was allowed to survive this scenario. In the current CLR the process is terminated in case of an unhandled exception on the finalizer thread.
Keep in mind that you should only implement a finalizer if you really need one and even then you should do a little as possible in the finalizer. But if whatever work your finalizer must do could throw an exception, you need to pick between the lesser of two evils. Do you want to shut down the application due to the unhandled exception? Or do you want to proceed in a more or less undefined state? At least in theory the latter may be the lesser of two evils in some cases. In those case the empty catch block would prevent the process from being terminated.
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.
An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.
There are situations where you might use them, but they should be very infrequent. Situations where I might use one include:
exception logging; depending on context you might want an unhandled exception or message posted instead.
looping technical situations, like rendering or sound processing or a listbox callback, where the behaviour itself will demonstrate the problem, throwing an exception will just get in the way, and logging the exception will probably just result in 1000's of "failed to XXX" messages.
programs that cannot fail, although they should still at least be logging something.
for most winforms applications, I have found that it suffices to have a single try statement for every user input. I use the following methods: (AlertBox is just a quick MessageBox.Show wrapper)
public static bool TryAction(Action pAction)
{
try { pAction(); return true; }
catch (Exception exception)
{
LogException(exception);
return false;
}
}
public static bool TryActionQuietly(Action pAction)
{
try { pAction(); return true; }
catch(Exception exception)
{
LogExceptionQuietly(exception);
return false;
}
}
public static void LogException(Exception pException)
{
try
{
AlertBox(pException, true);
LogExceptionQuietly(pException);
}
catch { }
}
public static void LogExceptionQuietly(Exception pException)
{
try { Debug.WriteLine("Exception: {0}", pException.Message); } catch { }
}
Then every event handler can do something like:
private void mCloseToolStripMenuItem_Click(object pSender, EventArgs pEventArgs)
{
EditorDefines.TryAction(Dispose);
}
or
private void MainForm_Paint(object pSender, PaintEventArgs pEventArgs)
{
EditorDefines.TryActionQuietly(() => Render(pEventArgs));
}
Theoretically, you could have TryActionSilently, which might be better for rendering calls so that an exception doesn't generate an endless amount of messages.
You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.