Is is possible to know if a certain exception can be thrown inside a code block?
The premise: Assume you are working on some old codebase and you have something like this.
try{
a lot of code that calls a bunch of other methods
}
catch (CustomException e){
some handling
}
I want to know what code in the try block that can throw this exception. For all I know nothing is throwing it anymore and this is just dead code. I know this is caused by bad code design, but when working with real code it is not always possible to prioritize refactoring all of the old code.
So in short, is it possible to tell at compile time if anything in the try block actually throws that exception?
(if it matters I am coding in idea rider)
Edit: stackoverflow thinks this question already has an aswer to this question, but in reality that question does not have a good answer to anything.Question
No there is no automatic technique
Yes there is a manual techniques: You look at the definition of the reference: for .net component you see in comment the input args, return and exceptions susceptible to trigger, but this is manual approach that must be done on all targeted methods.
If your target code has undefined behavior, I suggest that you enhance your exception handling on time, and start with most generic exception in your first version.
You log the content of exception analyse what is it then add this new type of exception in your error handling.
in all the case if you let general exception in the end of catch you will catch everything and this is a current practice.
While your answer describes a method to handle the situation, it is not really an answer to the question. – Fildor
Yes it is an answer, do you know an automatic technique to list all Exceptions that can be triggered on a target code ?
But in existing code it might be pretty dangerous to remove a catch block that handles a specific exception in a specific way. – Chippen
Where do I suggest tor Remove a catch block ? If your target code already catches an exception, your caller code is not impacted by it as it will not see any exception, and there is no use to do this.
If however you see explicitly in the target code that an exception is triggered with static code analysis, and if you want to see how to trigger it, you can design a unit test and create a scenario with special input to specifically trigger the code path, and to expect the exception in the test definition.
In fact there is a problem of understanding between your question and my answer.
You want to ask.:
For a given exception type, is there a way to know that a given target code can throw this exception. Answer is you must analyse it manually or try to fuzz.
My initial answer target another question which would be: for a given target code is it possible to know all exceptions that could be triggered.
Related
Recently I have used Global exception handling in my code and I came to know that with this all exceptions can be handled. Previously I was using try-catch at each controller and now I have removed all the try-catch from controller because of Global exception as it can handle all types of exception.
So I doubt that, is it a good practice to remove all the exception handling I have previously used in the controller for Global Exception handling or should use both Global, as well as try-catch at the controller.
And if try-catch is required, is it necessary that all the exceptions are to be handled at the controller level.
My current working stack is - .Net Core.
The question is too broad to give a full answer but, let me give my opinion on this matter.
try-catch-finally blocks are not used to handle unhandled exceptions. Naturally the cases that you never thought of will be unhandled and you should not keep them silent but you should allow them to express themselves for you to think about them. Handled exceptions though are the cases that are not at the hand of the programmer but he/she has thought about them. For example user input is string instead of number.
If it's the case that you thought but is in your control always check with ifs. For example if something can be null. Try-catch is really costly and no logic should be handled in them.
Using a global exception handler on the other hand is the exact opossite. It is not to wrap all thought cases and show a single response to user. You should log unknown exceptions to come back and think about why they happened and in the mean time say that you are sorry to user. :)
I've started playing with Code Contracts for .NET.
I have installed the msi.
In my sample Console application, in project properties, I have set "Assembly Molde" to "Standard Contract Requires".
I have checked "Perform Runtime Contract Checking" to "Full".
Having this settings, I'm using the very standard Contract.Require() in my code. I cannot put it in a try block, because it should be placed on the very top of the method's body. So, my question is how I handle the exceptions that it may throw, when the "Require()" condition is not satisfied?
With correct input, my code runs well, with the intended bad input, it throws an unhanded exception. I think I'm missing some pieces in the big picture here, or maybe my project's contract options are not set well.
Thanks for your help.
So, my question is how I handle the exceptions that it may throw, when the "Require()" condition is not satisfied?
You never handle that exception in production code because that exception is never thrown in a correct program. The exception exists to tell the caller that they're doing it wrong and they cannot ship their code to customers until it is fixed. If the exception is never thrown then there is never any need to handle it.
In test code, you do whatever your test framework does to represent "I expect this code to throw the following exception under the following error conditions".
Now, these facts imply something about the design of your code which uses code contracts, namely, there must be a way for the caller to know that they're not going to violate the contract without trying it and catching the failure.
I call exceptions thrown by badly-designed programs which require the caller to handle the failure "vexing exceptions". That is, you should never design a program like this:
private Phase PhaseOfMoon() { ... }
public void M()
{
Contract.Requires(this.PhaseOfMoon() != Phase.Full);
See, the caller has no way of knowing what your private method is going to do, so the caller must catch the exception. You need to make sure that the caller always has a way to guarantee that the exception will not be thrown or the Require precondition will not be violated.
In short: your responsibility is to give them a way to avoid the exception; their responsibility is to avoid it. No one's responsibility is to handle it.
So I have been doing some research into how I should be doing try-catch-finally blocks and there is some conflicting information in every post I read. Can someone clarify?
One common idea is to not catch exceptions that you do not know what to do with at that point in the code. The exception will bubble up until it presumably gets to a global exception handler if nothing else catches it. So at that point you display a message to the user that an unknown type of exception occurred, log it, etc.
Now after reading it sounds like this is the only exception handler that you will need? You should not be using it for flow control, so you should be checking if something is returned as null or is invalid causing the exception and correcting it in code. ie. testing for null and doing something about it before it can cause the exception.
But then there are other things such as running out of memory that you would not be able to test for, it would just occur during an operation and the exception would be thrown. But I would not be able to do anything about this either so this would be bubbled up to the global handler.
I think there are some that I am missing, like when dealing with files there can be some thrown from the external code. File not found exception seems like one that may come up often, so I would catch it and in the finally block gracefully close down anything I opened related to other code/processing and then notify the user and log it right there?
The only reason why you would want to catch an exception is for the finally part of the block to make sure that whatever you started before the exception is closed/finalized in a known state? But even then you would want to throw this exception after performing these tasks so the user is notified by the global exception handler, there is no point duplicating this code at this point?
So other than a global exception handler you would have try-catch-finally blocks for these scenarios.
So assuming that I am missing something here, there may be the possibility that you want to try and catch a specific type of exception and then do something with it. I cannot think of anything that you would want to do in the catch block though since the global one would log/notify the user and if you have an exception that usually means that there is no deal for the code to continue on.
Is there any easy way to know which exceptions will be thrown from which modules? I think the only way I have read is to read the MSDN or component suppliers documentation, other than that there is no way to know what exception you would be trying to catch if you were looking for a specific one (not sure why you would)
This question came up since in my application I had a section of code in a try-catch block, and it ended up that when an exception occurred it was either because an object was null, or a string was invalid. Once I wrote code to handle those scenarios the try-catch block is no longer needed, if an exception is encountered now there is nothing the code can do to recover so it should be logged and let the user know so it can be fixed.
But this goes against what I have been reading and what has been preached to me, bad code is code with no try-catch blocks. So how does this all tie together and what piece am I missing here?
The first part of your question is all correct: you should only catch exceptions that you know how to handle. Otherwise, just let them bubble up until they reach code that can handle them.
(Note that "handle" doesn't mean "log" or "display an error". It means to correct the problem that caused the exception, or work around it in some way.)
If they never encounter code that can handle them, or if they are unhandlable exceptions (like OutOfMemory), then they will eventually reach the global unhandled exception handler. This is where you will log the exception (if appropriate), display a generic error to the user (if appropriate), and more often than not, terminate the application. You cannot simply continue as if nothing happened—the exception indicates that the application is in an unexpected state. If you try and continue, you're just going to crash, or worse.
I think there are some that I am missing, like when dealing with files there can be some thrown from the external code. File not found exception seems like one that may come up often, so I would catch it and in the finally block gracefully close down anything I opened related to other code/processing and then notify the user and log it right there?
FileNotFound is a good example of an exception that you will want to handle locally. In the same method (or perhaps one level up, in your UI code) that attempts to load the file, you'll have a catch block for FileNotFound exceptions. If appropriate, display a friendly error message to the user and ask them to choose another file. If it's internal code, give up and try something else. Whatever you need to do. There are few good reasons for FileNotFound to bubble up outside of your code.
This is sort of like using exceptions for flow control, but unavoidable. There is no way to avoid using exceptions (or error codes) for I/O, so you just need to handle the failure case. You could try and verify that the file exists first, before trying to open it, but that would not solve the race issue wherein the file gets deleted or becomes otherwise inaccessible between the time your verification code runs and when you actually try and open it. So now all you've done is duplicated your error-handling code in two places, which serves little purpose.
You have to handle exceptions like FileNotFound locally. The further away from the code that throws, the less likely you can do anything reasonable about it.
Another good example of this, aside from I/O-related exceptions, is a NotSupportedException. For example, if you try to call a method that isn't supported, you might get this exception. You will likely want to handle it and have code in the catch block that falls back to a safe alternative.
The only reason why you would want to catch an exception is for the finally part of the block to make sure that whatever you started before the exception is closed/finalized in a known state? But even then you would want to throw this exception after performing these tasks so the user is notified by the global exception handler, there is no point duplicating this code at this point?
This does not require catching the exception. You can have a try block with only a finally block. A catch block is not required. In fact, this is precisely what using statement implements. If you have state that needs to be cleaned up in the event of an exception being thrown, you should implement the IDisposable pattern and wrap usage of that object in a using block.
Is there any easy way to know which exceptions will be thrown from which modules? I think the only way I have read is to read the MSDN or component suppliers documentation, other than that there is no way to know what exception you would be trying to catch if you were looking for a specific one (not sure why you would)
Precisely. This is not really a problem, though, since you are only catching the exceptions that you can do something about. If you don't know that a module can throw a particular exception, you obviously can't have written code that can handle that exception.
The documentation will tell you all of the important exceptions that you might need to handle, like FileNotFound, SecurityException, or what have you.
This question came up since in my application I had a section of code in a try-catch block, and it ended up that when an exception occurred it was either because an object was null, or a string was invalid. Once I wrote code to handle those scenarios the try-catch block is no longer needed, if an exception is encountered now there is nothing the code can do to recover so it should be logged and let the user know so it can be fixed.
Avoiding exceptions in the first place is always the best option. For example, if you can design your application so that a null object or invalid string is impossible, great. That is what we call robust code. In that case, you don't need to catch these exceptions because there's no way that you can handle it. You thought you already handled the problem, so if an exception is getting thrown anyway, it is a sign of a bug. Don't gloss over it with a catch block.
But sometimes, catch blocks are still necessary, and you write code inside of the catch block to handle the problem. In that case, there's probably no reason to re-throw the exception or log it, so you don't have any code duplication.
But this goes against what I have been reading and what has been preached to me, bad code is code with no try-catch blocks. So how does this all tie together and what piece am I missing here?
Completely wrong. I don't know where you've been reading that, but it is nonsense. Exceptions are exceptional conditions. If your code has catch blocks strewn all over it, that is a sign that you are doing it wrong. Either you're using exceptions for flow control, you're swallowing exceptions in a misguided attempt to "improve reliability", or you don't know about the global unhandled exception handler.
Doesn't sound like you're missing anything to me.
The only thing I feel compelled to mention that doesn't fit strictly into any of your questions is that sometimes you might want to catch an exception and rethrow it as a different exception. The most common situation where you would do this is if you were designing a library of re-usable code. Inside of the library, you might catch internal exceptions and, if you cannot handle them, rethrow them as general exceptions. The whole point of a library is encapsulation, so you shouldn't let exceptions bubble up that the caller cannot possibly do anything about.
There is no true guide for exceptions management (raising and handling). Every app has to decide what level of flow control should be used and how exception has to be raised/handled.
General rules are:
exceptions are raised in exceptional situations
handle exception you can handle and do meaningful things for your app so
exception raising can be used in flow control, actually it's the only way you can reliably handle flow control when you are dealing with devices, so hardware interrupts. (printers, bill validators, file transfer...)
The rest is up to you. The meaning of exception management is made by you.
Imagine you need to download some files from an FTP server, one you don't control. Of course you can't trust other people so you need to prepare for temporary outages and such. So you wrap your downloading code in a try-catch-block and look for WebException if you catch one you might check for FtpStatusCode.ActionNotTakenFileUnavailableOrBusy if that was the error you simply retry. Similarly if you call a web service a 404 might be trouble, but a 429 means that you wait a little and retry, because you had been rate-limited.
Usually you can know which exceptions can be thrown by experience or documentation but C# lacks checked exceptions. Things like NullPointerException or ArgumentNullException can be properly handled with guards in your code. But other things, like errors external dependencies can sometimes be caught and handled by you without crashing the application.
I'm new in a developement for Windows 8 and C#, but I have certain experience with Java Programming.
So, when I try to make some Json parser (for example) in java, I can't do it without use a try - catch block, and this way I can handle the exception, but when I try to do the same in c# (Windows 8) and I don't use the try - catch block it works too, like this:
if (json != null)
{
JObject jObject = JObject.Parse(json);
JArray jArrayUsers = (JArray)jObject["users"];
foreach (JObject obj in jArrayUsers)
{
ListViewMainViewModel user = new ListViewMainViewModel(
(String)obj["email"],
(String)obj["token"],
(String)obj["institution"],
(String)obj["uuidInstitution"]);
usersList.Add(user);
}
return usersList;
}
}
As I know the right way is to catch JsonReaderException, but Visual Studio never warned me on that. I would like to know if there's a easy way to know if some method throw an exception, like is on java using eclipse (it's mandatory implement try-catch block or code wont compile)
You will have to consult the documentation for that. C# lacks a throws keyword.
The term for what you are looking for is checked exceptions, and more info can be found in the C# FAQ.
In C# you are responsible for handling exceptions - which IMHO is the better way of going about it than the Java implementation. In effect, an exception should be, well exceptional, that is: It isn't something you should just always expect to happen.
Consider this weirding (yet, common) anti-pattern:
try {
} catch (Exception ex) { /* Handler goes here */ }
What exactly does that mean? Are you really going to handle every single exception that passes through here? Even stuff like OutOfMemoryExceptions? That's nuts. The only thing this sort of pattern will lead to is suppressing legitimate exceptions that really ought to bring down the application - this is fairly similar to the Java approach.
Think of an Exception as being a flag to the programmer that says 'hey, the environment just entered an impossible state'. For example, if I try to divide by zero and the system throws a DivideByZeroException, then rightly the system should alert you to this, because this is a failure - one the system can't just 'figure it's way out of' - and if you simply suppress the issue, how is that really helping? In the end this is counter-productive, in that all you're doing is masking over what is really an impossible application state. If you do this a lot in your application, then it eventually just devolves into a sludge of toxic wrong-ness. Yuck!
Exceptions also take up a lot of screen real estate. Sometimes I wish they would make the try/catch/finally blocks a little more streamlined, but then I remember that doing so would encourage people to use them more, so I repent of that position pretty quick.
Exceptions are useful programmer-to-programmer notifications saying that something you're doing doesn't make sense. Obviously we should never pass raw exceptions to the user because they won't know what to do with them. At the same time, you don't want to try to handle every single exception on the face of the earth, because 'handling' in this sense typically transforms into 'suppression', which is way worse than just letting the application fail (gracefully).
C#, as has been mentioned, does not have checked exceptions, and thank goodness.
The idea of checked exceptions sounds great on its face, but talk to anyone who is forced to use them by language or runtime, and they'll say there are three big problems with checked exceptions:
They impose their will upon the consuming coder. Checked exceptions, by their definition, are expected to be handled before they are thrown out of the runtime. The runtime is in effect telling the coder "you should know what to do when I throw this, so do so". First off, think about it; you are told to expect something that happens in exceptional cases by its very definition. Second, you're expected to somehow handle it. Well, that's all well and good when you actually have the ability to address the problem the exception indicates. Unfortunately, we don't always have that ability, nor do we always want to do everything we should. If I'm writing a simple form applet that performs a data transformation, and I just want my application to die a fiery death if there's any problem, I can't just not catch anything; I have to go up all possible call stacks of every method that could throw something and add what it could throw to the throws clause (or be extremely lazy and put a "throws Exception" clause on every method of my codebase). Similarly, if my app is constructed such that I can't throw out a particular exception, perhaps because I'm implementing an interface beyond my control that doesn't specify it as a potential throwable, then my only options are to swallow it entirely and return a possibly invalid result to my callers, or to wrap the exception in an unchecked throwable type like a RuntimeException and throw it out that way (ignoring the entire checked exception mechanism, which is not recommended of course).
They violate SOLID, especially the Open-Closed Principle. Make a change that adds a checked exception to your code, and if you can't handle said exception, all usages of your method must either handle it or mark themselves as throwing the exception. Usages which rethrow must be handled by their own callers or they have to be marked as throwing the same exception. By making a change as surgical as calling an alternate method in a particular line of code, you now have to trace up all possible call stacks and make other changes to code that was working just fine, just to tell them your code could conceivably throw an exception.
They create leaky abstractions by definition. A caller consuming a method with a "throws" clause must, in effect, know these implementation details about its dependency. It must then, if it is unwilling or unable to handle these errors, inform its own consumers about these errors. The problem is compounded when the method is part of an interface implementation; in order for the object to throw it, the interface must specify it as a throwable, even if not all of the implementations throw that exception.
Java mitigates this by having a multilevel hierarchy of Exception classes; all I/O-related exceptions are (supposed to be) IOExceptions, for instance, and an interface with methods that have IO-related purposes can specify that an IOException can be thrown, relieving it of the responsibility to specify each specific child IOException. This causes almost as many problems as it solves, however; there are dozens of IOExceptions, which can have very different causes and resolutions. So, you must interrogate each IOException that you catch at runtime to obtain its true type (and you get little or no help identifying the specific ones that could be thrown) in order to determine whether it's something you can handle automatically, and how.
EDIT: One more big problem:
They assume try-catch is the only way to handle a possible exception situation. Let's say you're in C# in an alternate universe where C# has Java-style checked exceptions. You want your method to open and read a file given a filename passed into it by the caller. Like a good little coder, you first validate that the file exists in a guard clause, using File.Exists (which will never throw an exception; in order to return true, the path must be valid, the file specified at the path must exist, and the executing user account must have at least read access to the folder and file). If File.Exists returns false, your method simply returns no data, and your callers know what to do (say this method opens a file containing optional config data, and if it doesn't exist, is blank or is corrupted, your program generates and uses a default configuration).
If the file exists, you then call File.Open. Well, File.Open can throw nine different types of exceptions. But none of them are likely to occur, because you already verified using File.Exists that the file can be opened read-only by the user running the program. The checked exception mechanism, however, wouldn't care; the method you're using specifies it can throw these exceptions, and therefore you must either handle them or specify that your own method can throw them, even though you may take every precaution to prevent it. The go-to answer would be to swallow them and return null (or to forget the guard clause and just catch and handle File.Open's exceptions), but that's the pattern you were trying to avoid with the guard clause in the first place.
None of this even considers the potential for evil. A developer might, for instance, catch and encapsulate an unchecked exception as a checked one (for instance, catching a NullPointerException and throwing an IOException), and now you have to catch (or specify that your method throws) an exception that isn't even a good representation of what's wrong.
As far as what to use instead in C#, the best practice is to use XML documentation comments to inform the immediate caller using your method that an exception could potentially be thrown from it. XML-doc is the .NET equivalent to JavaDoc comments, and is used in much the same way, but the syntax is different (three forward slashes followed by the comments surrounded with a system of XML tags). The tag for an exception is easy enough to specify. To efficiently document your codebase, I recommend GhostDoc. It will only generate exception comments for exceptions explicitly thrown from inside the method being documented, however, and you'll have to fill in some blanks.
I'm not a java developer, but from the answers here it seems as though the Java implementation is a burden to clients of those methods. However, C# missed an opportunity (Java-like or otherwise) to communicate to the caller the type of exceptional outcomes that could happen, as authored by the developer of the method, allowing me the caller to handle it appropriately.
Since this construct isn't built into the language, I would suggest to library developers that you adopt a wrapper class and use it as the return type for any methods that could go awry. Using said class as the return type in lieu of exceptions, clients can reason about what to expect when calling the method, as it is clearly defined in the method signature. Also, using the wrapper would allow a method to tell a client why something went awry in a way does not break the flow like exceptions do.
More on this subject here: http://enterprisecraftsmanship.com/2015/03/20/functional-c-handling-failures-input-errors/
I've been given a task to create a general exception handling code snippet, I have a couple of questions:
Is it a good idea? General exception handling leads to generalized messages as to what's breaking, making tracking hard.Leading to :
What should I include in the snippet? I figure less is more here but adding a log seems to be a good idea because I don't think the exception messages are going to be very specific.
I wouldn't say it's a good idea, no. I tend to have relatively few exception handlers in my code. They're typically there to:
Occasionally convert an exception of one type into another (although that's rarer in C# than in Java; whether it's a good thing or not is a different discussion)
Catch errors at the root of the stack for a particular request / user action / whatever, usually just logging the result
Handle bone-headed APIs which throw exceptions in non-exceptional situations
None of these takes long to write, and none of them comes up so often that it's worth having a common snippet.
Having a set of documented conventions around exception handling - with a discussion of the design in the same document - is a good idea though.
it's better to add specific exception handling and including logs... But, you can add the general exception as well, to catch all unknown exceptions.
Stack traces (to those who can read them) are 90% of what you need. Including the parameters passed into the erroring method will also GREATLY help in debugging. If this is logging to a database, please be careful about logging sensitive pieces of data (PII or PHI).
If this is a web application, I would recommend saving a snapshot of the session as well, this can also help greatly in debugging.
I would recommend you to use Code Contracts and AOP tools like PostSharp. They both provide great possibilities to debug and error-handle your code.
I always use these guidelines as what should be handled by exceptions and what should not. Also, it's hard to get exceptions right.
What I usually end up with is code that has few, if any specific exception handlers, and a global catch-all handler, that just logs the exception (including the stack trace).
That said, when you do use local exception handling, and if the default try.snippet is lacking, something like this might work (just the code included, the rest of the .snippet file is a bit obvious):
try
{
$selected$
}
catch ($caughtExceptionType$Exception ex)
{
$end$
Logger.Error("$message", ex);
//throw new $customExceptionType$Exception("$message", ex);
}
I think that a general exception handler strategy is only applicable at the entry points in the code that you'd like to treat unhandled exceptions. Maybe in a Main method for single-threaded application code or in the AppDomain.UnhandledException event.
Then, the strategy to use is highly application specific. Maybe you have a central log to add the information to, or a message queue that will trigger further processing (e.g., insert in a database and inform an administrator).