How to use Java-style throws keyword in C#? - c#

In Java, the throws keyword allows for a method to declare that it will not handle an exception on its own, but rather throw it to the calling method.
Is there a similar keyword/attribute in C#?
If there is no equivalent, how can you accomplish the same (or a similar) effect?

The op is asking about the C# equivalent of Java's throws clause - not the throw keyword. This is used in method signatures in Java to indicate a checked exception can be thrown.
In C#, there is no direct equivalent of a Java checked exception. C# has no equivalent method signature clause.
// Java - need to have throws clause if IOException not handled
public void readFile() throws java.io.IOException {
...not explicitly handling java.io.IOException...
}
translates to
// C# - no equivalent of throws clause exceptions are unchecked
public void ReadFile()
{
...not explicitly handling System.IO.IOException...
}

In Java, you must either handle an exception or mark the method as one that may throw it using the throws keyword.
C# does not have this keyword or an equivalent one, as in C#, if you don't handle an exception, it will bubble up, until caught or if not caught it will terminate the program.
If you want to handle it then re-throw you can do the following:
try
{
// code that throws an exception
}
catch(ArgumentNullException ex)
{
// code that handles the exception
throw;
}

Yes this is an old thread, however I frequently find old threads when I am googling answers so I figured I would add something useful that I have found.
If you are using Visual Studio 2012 there is a built in tool that can be used to allow for an IDE level "throws" equivalent.
If you use XML Documentation Comments, as mentioned above, then you can use the <exception> tag to specify the type of exception thrown by the method or class as well as information on when or why it is thrown.
example:
/// <summary>This method throws an exception.</summary>
/// <param name="myPath">A path to a directory that will be zipped.</param>
/// <exception cref="IOException">This exception is thrown if the archive already exists</exception>
public void FooThrowsAnException (string myPath)
{
// This will throw an IO exception
ZipFile.CreateFromDirectory(myPath);
}

Here is an answer to a similar question I just found on bytes.com:
The short answer is no. There are no checked exceptions in C#. The
designer of the language discusses this decision in this interview:
http://www.artima.com/intv/handcuffs.html
The nearest you can get is to use the tags in your XML
documentation, and distribute NDoc generated docs with your
code/assemblies so that other people can see which exceptions you throw
(which is exactly what MS do in the MSDN documentation). You can't rely
on the compiler to tell you about unhandled exceptions, however, like
you may be used to in java.

After going through most of the answers here, I'd like to add a couple of thoughts.
Relying on XML Documentation Comments and expecting others to rely on is a poor choice. Most C# code I've come across does not document methods completely and consistently with XML Documentation Comments. And then there's the bigger issue that without checked exceptions in C#, how could you document all exceptions your method throws for the purpose of your API user to know how to handle them all individually? Remember, you only know about the ones you throw yourself with the throw keyword in your implementation. APIs you're using inside your method implementation might also throw exceptions that you don't know about because they might not be documented and you're not handling them in your implementation, so they'll blow up in face of the caller of your method. In other words, these XML documentation comments are no replacement for checked exceptions.
Andreas linked an interview with Anders Hejlsberg in the answers here on why the C# design team decided against checked exceptions. The ultimate response to the original question is hidden in that interview:
The programmers protect their code by writing try finally's everywhere, so they'll back out correctly if an exception occurs, but they're not actually interested in handling the exceptions.
In other words, nobody should be interested in what kind of exception can be expected for a particular API as you're always going to catch all of them everywhere. And if you want to really care about particular exceptions, how to handle them is up to you and not someone defining a method signature with something like the Java throws keyword, forcing particular exception handling on an API user.
--
Personally, I'm torn here. I agree with Anders that having checked exceptions doesn't solve the problem without adding new, different problems. Just like with the XML documentation comments, I rarely see C# code with everything wrapped in try finally blocks. It feels to me though this is indeed your only option and something that seems like a good practice.

Actually not having checked exceptions in C# can be considered a good or bad thing.
I myself consider it to be a good solution since checked exceptions provide you with the following problems:
Technical Exceptions leaking to the business/domain layer because you cannot handle them properly on the low level.
They belong to the method signature which doesn't always play nice with API design.
Because of that in most bigger applications you will see the following pattern often when checked Exceptions occur:
try {
// Some Code
} catch(SomeException ex){
throw new RuntimeException(ex);
}
Which essentially means emulating the way C#/.NET handles all Exceptions.

You are asking about this :
Re-throwing an Exception
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
or
static void Main()
{
string s = null;
if (s == null)
{
throw new ArgumentNullException();
}
Console.Write("The string s is null"); // not executed
}

There are some fleeting similarities between the .Net CodeContract EnsuresOnThrow<> and the java throws descriptor, in that both can signal to the caller as the type of exception which could be raised from a function or method, although there are also major differences between the 2:
EnsuresOnThrow<> goes beyond just stating which exceptions can be thrown, but also stipulates the conditions under which they are guaranteed to be thrown - this can be quite onerous code in the called method if the exception condition isn't trivial to identify. Java throws provides an indication of which exceptions could be thrown (i.e. IMO the focus in .Net is inside the method which contracts to prove the throw, whereas in Java the focus shifts to the caller to acknowledge the possibility of the exception).
.Net CC doesn't make the distinction between Checked vs Unchecked exceptions that Java has, although the CC manual section 2.2.2 does mention to
"use exceptional postconditions only for those exceptions that a caller
should expect as part of the API"
In .Net the caller can determine whether or not to do anything with the exception (e.g. by disabling contracts). In Java, the caller must do something, even if it adds a throws for the same exception on its interface.
Code Contracts manual here

If the c# method's purpose is to only throw an exception (like js return type says) I would recommend just return that exception. See the example bellow:
public EntityNotFoundException GetEntityNotFoundException(Type entityType, object id)
{
return new EntityNotFoundException($"The object '{entityType.Name}' with given id '{id}' not found.");
}
public TEntity GetEntity<TEntity>(string id)
{
var entity = session.Get<TEntity>(id);
if (entity == null)
throw GetEntityNotFoundException(typeof(TEntity), id);
return entity;
}

For those wondering, you do not even need to define what you catch to pass it on to the next method. In case you want all your error handling in one main thread you can just catch everything and pass it on like so:
try {
//your code here
}
catch {
//this will throw any exceptions caught by this try/catch
throw;
}

Related

What are exceptions and why "throw" them?

I've read many sites and other responses on StackOverflow, but I still haven't grasped the the importance of exception handling and why we "throw" them.
For this post, my understanding of an exception can best be described as:
"An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running..." https://www.tutorialspoint.com/csharp/csharp_exception_handling.htm
When handling exceptions, I often see the following code snipets:
try
{
// Do something that causes an Exception
}
catch (Exception)
{
// Could have error logging here
throw;
}
If you do not perform any error logging, why have the "try/catch" and "throw" statement? The code will still throw an exception regardless of whether I try/catch. I must be missing something. What does "throwing" do?
I've included a basic divide by zero scenario in the following:
https://repl.it/BjgV/24. When you remove the "try/catch/throw" you see the same results.
Something to keep in mind is not only that caught exceptions can be used for logging errors, they can be used for handling errors that might arise.
Let's say you have some kind of Widget object, that has properties you initialize via arguments to a constructor:
public class Widget
{
public string Name;
Widget(string widgetName)
{
if (widgetName != "")
Name = widgetName;
else
throw new ArgumentException("Name must be provided for widget.");
}
}
In this case, we have a situation where we want to require our Widget have a name when it's instantiated - we check the argument to see if it's blank, and we throw an ArgumentException to indicate that something is wrong with one of the arguments to the constructor, as well as include a helpful message about what specifically went wrong.
This means we can then have context-specific validation logic in a wrapper, rather than having to have everything crammed into our base Widget class:
public Widget ForCaseA (string widgetName)
{
Widget w;
try {
w = new Widget(widgetname);
}
catch (ArgumentException as argEx) // We're specifically catching the subtype of ArgumentExceptions; generic Exceptions or other types of exception wouldn't be caught here and would bubble up out of this try/catch block.
{
// At this point, we could look at the specific data in the exception object to determine what needs to happen to resolve the exception. Since there's only one argument and it's throwing an ArgumentException, we know it's going to be a problem with a bad widgetName. In this case, we can say 'well, in this specific case, we want to give it a default widget name'.
w = new Widget("DefaultName");
}
return w;
}
One of the ways catching exceptions by type becomes exceptionally useful is when you use inheritance to create your own types based off the generic Exception class; e.g. giving your Widgets a WidgetException. This lets you catch issues specific to your class/entity (like the widget's name), but doesn't have to handle issues that fall outside the scope of the Widget itself.
"Throwing" is sometimes (in non-oop languages) the same as "raising" an error.
If we catch an exception, we might want to bubble that up to some method higher in the callstack, and perhaps generalize it more in the process. Thus, we might use something like:
try { doSomething(); }
catch (VerySpecificException ex) {
throw new SomeGenericException(ex);
}
This allows us to expect only generic exceptions in the higher-level programming, while maintaining a full stack trace and inner exceptions so we can see where it came from.
Throw, on it's own (such as in your example), simply pushes the error up to the next caller, with no changes. In your exact example, you might just leave out the try/catch altogether, as the result will be the same (the exception gets pushed to the next block: excepting maybe if you have some AOP or weaving in there to handle it, but that's a bit beyond this answer I think).
If there's no try/catch block, the exception is pushed back up to the next method in the callstack. If there's no try/catch blocks anywhere, the exception is said to be "unhandled", and your application crashes. There's no excuse for an unhandled exception to make it to the top.
Specifically regarding this part:
If you do not perform any error logging, why have the "try/catch" and "throw" statement?
Aside from logging the exception, in some situations you may want to:
Wrap the exception in a meaningful user-defined exception which you throw to raise some error.
Release certain resources just in case the exception happens and bubble it up for potential handling somewhere else.
These are just two examples.

Exception throws: encapsulate them or not?

Once I read an MSDN article that encouraged the following programming paradigm (its not 100% true... see edit):
public class MyClass
{
public void Method1()
{
NewCustomException();
}
public void Method2()
{
NewCustomException();
}
void NewCustomException()
{
throw new CustomException("Exception message");
}
}
Do you think this paradigm makes sense? Wouldn't it be enough to store the exception message in a static const field and then pass it to the exception's constructor, instead of encapsulating the whole exception throw?
EDIT:
Use exception builder methods. It is
common for a class to throw the same
exception from different places in its
implementation. To avoid excessive
code, use helper methods that create
the exception and return it.
I just noticed (see citation), that the article tells to return an exception:
public class MyClass
{
public void Method1()
{
throw NewCustomException();
}
public void Method2()
{
throw NewCustomException();
}
CustomException NewCustomException()
{
return new CustomException("Exception message");
}
}
What do you think about this?
My understanding is that passing an exception instance around is a faux pas if for no other reason than you lose the stack trace associated with the exception. Calling another method would change the stack trace and thereby make it effectively useless. I'd recommend at a minimum getting the stack trace off the exception and passing it as an argument to some helper if that's the road you're going to go down.
That's a refactor too far in my book. You have to go back up a line in the stack trace to see exactly where the problem occured. If your custom exception is always using the same message, put it in the CustomException class. If it's only the same within the code you've quoted, then yes, put it in a const field (you can't have static const - it's implicitly static).
Another problem you get doing that is that there will be lots of places where you wont even be able to throw an exception because the compiler wont allow it. Consider these two methods added to your class:
public string GetFoo1(bool bar)
{
if (bar)
return "";
else
NewCustomException();
}
public string GetFoo2(bool bar)
{
if (bar)
return "";
else
throw new CustomException("Exception message");
}
GetFoo1 will not compile while GetFoo2 will.
I would have a method that builds an Exception, rather than one that throws it. As in the sample below. I seem to remember seeing a Microsoft guideline that recommended this, but I can't remember where.
With this technique, if you want to change the exception type for any reason, you only need to do so in one place (e.g. a change from ConfigurationException to ConfigurationErrorsException when upgrading from .NET 1.x to .NET 2.0).
Also you respect the DRY principle by having a single copy of the code that builds the exception with its message and any other data included in the exception.
You obviously wouldn't do this in trivial cases (e.g. you wouldn't replace throw new ArgumentNullException("myParamName") by throw BuildArgumentNullException("myParamName"))
private static Exception BuildSomeException(... parameters with info to include in the exception ...)
{
string message = String.Format(...);
return new SomeException(message, ...);
}
...
throw BuildSomeException(...);
I don't see the point of making a method that simply throws an exception. But, I do think trowing custom exceptions has value. If all of the exceptions you throw are children of a custom exception, it allows you to quickly see if the thrown exception is one you are accounting for or something you have not handled yet. Also, you can then catch MyBaseException and it is not as bad as catching Exception.
It is handy to do this if you don't know how you plan to handle exceptions, exactly. Do you want to just throw it? Or perhaps later you are going to log the exception somewhere then throw it? Or maybe pass some arguments (i.e. method name, etc.) that get bundled in with the exception?
In this case, creating a separate method that handles the exception situation is convenient when you want to change it.
I don't usually bother with this - instead, just figure out upfront how you are going to handle exceptions (i.e. what string information you are going to putin the message).
I generally prefer to store exception messages as resources. That serves several purposes:
If the requirement comes down to localize exception messages, it's a no-brainer.
Exception messages tend to be more standardized across developers since it's extra work to create a new, but only slightly different message.
If you ensure that messages are referenced by an identifier, and include the identifier with the exception when it's thrown, then tracing a message to the code that threw it is easier.
Downside is it does require (just) slightly more effort up front than hard-coding the messages.

Does 'throw' or 'try...catch' hinder performance? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How slow are .NET exceptions?
I've been reading all over the place (including here) about when exception should / shouldn't be used.
I now want to change my code that would throw to make the method return false and handle it like that, but my question is: Is it the throwing or try..catch-ing that can hinder performance...?
What I mean is, would this be acceptable:
bool method someMmethod()
{
try
{
// ...Do something
catch (Exception ex) // Don't care too much what at the moment...
{
// Output error
// Return false
}
return true // No errors
Or would there be a better way to do it?
(I'm bloody sick of seeing "Unhandled exception..." LOL!)
Ask yourself the following question: Is the exception exceptional?
If this can happen in normal program flow, for example, a failure to parse a number typed by the user, don't use an exception.
If this should not normally happen, but rather signifies a problem outside the program's control, such as a missing file, use an exception.
If your question is whether or not the presence of a try...catch block will affect performance, then no.
If your question is whether there is a performance hit in using an exception-based model rather than a return value model, then yes, there is. Having a function like this:
public void DoWork()
{
if(something) throw new Exception(...);
}
Is not going to perform as well under error conditions as a function like this:
public bool DoWork()
{
if(something) return false;
return true;
}
Exceptions have to unwind the stack and kick you out to the nearest catch block in order to work, so there's overhead involved in that. It's simpler to return a status value, but it's also a more choppy interface to deal with when exceptions are not the rule.
However, that isn't the point. If you're writing code where exceptions are the rule, then you have a problem. Exceptions should be used in...exceptional...conditions, such as when you encounter a condition that you could not account for in code.
Consider the types like int and DateTime. These types provide (among others) two different functions for converting string values into corresponding int and DateTime values: Parse and TryParse. Parse uses the exception model, since it's assuming at that point that you'll be passing it a well-formed integer value, so if it gets something else, that's an exceptional condition. TryParse, on the other hand, is designed for when you are not sure about the format of the string, so it uses the return value model (along with an out parameter in order to get the actual converted value).
Exceptions are for exceptional cases. If your // ...Do something is throwing exceptions during normal flow, fix it.
If you have a try/catch block and this block does not throw an exception, it runs at the same speed as if you didn't have the try/catch block wrapping it. It's only when an exception is actually thrown does performance go down, but if you are using exceptions as designed, it doesn't matter as you are now in an exceptional situation. Exceptions should not be used for control flow.
Putting try...catch around code will not really hinder performance, code that may fail should always have a try...catch around it.
However, you should always avoid exceptions being thrown in the first place because these significantly hit performance.
Never throw an exception unless it is truly exceptional!
Your returning false implies a pattern similar to that used with the TryParse() method.
Its just that you shouldn't allow the exception to raise for logic i.e. you shouldn't leave the catch block with responsibility or returning false always. Simply putting, it should not be used for logic.
For example, when you can check for null and return false, you should not call method on null to have a NullReferenceException and let the catch block return false.
Its also a common misconception of developers to think catching Exception is a good idea.
If Exception happened to be a StackOverflowException or an OutOfMemoryException you probably
wouldnt want your application to continue in these cases.
Regarding performance, using exceptions to control program flow would hurt performance significant, partly because each time an exception is thrown the clr must walk the stack to find a catch statement (called stack unwinding)
The TryXXX pattern is one way of attempting to perform some action without an exception being thrown.
Performance-wise, you wouldn't see any difference. It's a micro-optimization to leave out try-catch because it's hindering performance.
However... That said, I'm not convinced your motives to do so are entirely valid. If the function that throws is your own, then I guess it's throwing for a reason and catching the exception might conceal an important error.
I often heard that Exceptions are slow when thrown the first time, as some module or whatever has to be loaded. But, as Blorgbeard said, Exceptions are for exceptional cases. It shouldn't matter.

throw new Exception vs Catch block

Is there any behavioural difference between:
if (s == null) // s is a string
{
throw new NullReferenceException();
}
And:
try
{
Console.Writeline(s);
}
catch (NullReferenceException Ex)
{ // logic in here
}
Both throw exceptions of null object, if s is null. The first example is more readable as it shows exactly where the error occurs (the exception bit is right next to the line which will cause the exception).
I have seen this coding style a lot on various blogs by various coders of all sorts of skill levels, but why not just perform the main logic by checking if s is not null and thus save the exception from ever being raised? Is there a downside to this approach?
Thanks
No, Console.WriteLine(null) won't throw an exception. It will just print nothing out. Now assuming you meant something like:
Console.WriteLine(s.Length);
then it makes sense... and you should use the first form. Exceptions should occur when you can't predict them ahead of time with your current information. If you can easily work out that something's wrong, it makes no sense to try an operation which is bound to fail. It leads to code which is harder to understand and performs worse.
So NullReferenceException, ArgumentNullException and the like shouldn't be caught unless they're due to a nasty API which sometimes throws exceptions which you can handle, but which shouldn't really be being thrown in the first place. This is why in Code Contracts, the default behaviour for a failed contract is to throw an exception which you can't catch explicitly, other than by catching everything (which is typically somewhere at the top of the stack).
As Jon Skeet already mentioned, Console.WriteLine (null) won't throw an exception.
Next to that, I'd like to say that you should 'fail fast'. That means that you have to put 'guard' clauses in your methods, and check the arguments that have been given in your methods if they can be considered to be valid.
This allows you to throw an exception yourself, and give an additional message which will be helpfull when debugging. The message can give a clear indication on what was wrong, and that is much handier then if you're faced with a NullReferenceException that has been thrown without any good information in it's message property.
If you are writing a class library there may be occasions when you know that if a certain parameter contains a null value, that may cause trouble further down the line. In those cases I usually find it to be a good idea to throw an exception (even though I would probably use ArgumentNullException for that case) to make the user of the class library aware of this as early and clearly as possible.
Exceptions are not always a bad thing.
Jon Skeet is right but, more generally, it's all a question of semantic.
If the situation has some applicative meaning (number out of bound, date of birth in the future, etc) you may want to test for it before doing any operation and throw a custom exception (that is one with meaning for your application).
If the situation is truly "exceptional", just write the code as if the given value were correct. See, if you put the test, you will do it everytime, knowing that the VM will do it anyway in case it needs to throw an exception. From a performance point of view, if the error happens to have a statistically small occurence, it makes no sense.
If you're taking a Design By Contract type approach to things then a piece of code can specify that it throws exceptions in order to specify its contract and to enforce it. The other half is, of course, calling code recognising the contract and fulfilling it.
In this case it would mean that if you know a method will throw an exception if you pass in null (i.e. its contract is that you don't pass nulls) then you should check before calling it.
Jon Skeet says that the method won't throw an exception anyway. That may or may not be true but the principle of guarding for method contract stands (which I believe was the point of your question).

Best practices for exception management in Java or C# [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'm stuck deciding how to handle exceptions in my application.
Much if my issues with exceptions comes from 1) accessing data via a remote service or 2) deserializing a JSON object. Unfortunately I can't guarantee success for either of these tasks (cut network connection, malformed JSON object that is out of my control).
As a result, if I do encounter an exception I simply catch it within the function and return FALSE to the caller. My logic is that all the caller really cares about is if the task was successful, not why it is wasn't successful.
Here's some sample code (in JAVA) of a typical method)
public boolean doSomething(Object p_somthingToDoOn)
{
boolean result = false;
try{
// if dirty object then clean
doactualStuffOnObject(p_jsonObject);
//assume success (no exception thrown)
result = true;
}
catch(Exception Ex)
{
//don't care about exceptions
Ex.printStackTrace();
}
return result;
}
I think this approach is fine, but I'm really curious to know what the best practices are for managing exceptions (should I really bubble an exception all the way up a call stack?).
In summary of key questions:
Is it okay to just catch exceptions but not bubble them up or formally notifying the system (either via a log or a notification to the user)?
What best practices are there for exceptions that don't result in everything requiring a try/catch block?
Follow Up/Edit
Thanks for all the feedback, found some excellent sources on exception management online:
Best Practices for Exception Handling | O'Reilly Media
Exception Handling Best Practices in .NET
Best Practices: Exception Management (Article now points to archive.org copy)
Exception-Handling Antipatterns
It seems that exception management is one of those things that vary based on context. But most importantly, one should be consistent in how they manage exceptions within a system.
Additionally watch out for code-rot via excessive try/catches or not giving a exception its respect (an exception is warning the system, what else needs to be warned?).
Also, this is a pretty choice comment from m3rLinEz.
I tend to agree with Anders Hejlsberg and you that the most callers only
care if operation is successful or not.
From this comment it brings up some questions to think about when dealing with exceptions:
What is the point this exception being thrown?
How does it make sense to handle it?
Does the caller really care about the exception or do they just care if the call was successful?
Is forcing a caller to manage a potential exception graceful?
Are you being respectful to the idoms of the language?
Do you really need to return a success flag like boolean? Returning boolean (or an int) is more of a C mindset than a Java (in Java you would just handle the exception) one.
Follow the error management constructs associated with the language :) !
It seems odd to me that you want to catch exceptions and turn them into error codes. Why do you think the caller would prefer error codes over exceptions when the latter is the default in both Java and C#?
As for your questions:
You should only catch exceptions that you can actually handle. Just
catching exceptions is not the right thing to do in most cases.
There are a few exceptions (e.g. logging and marshalling exceptions
between threads) but even for those cases you should generally
rethrow the exceptions.
You should definitely not have a lot of try/catch statements in your
code. Again, the idea is to only catch exceptions you can handle.
You may include a topmost exception handler to turn any unhandled
exceptions into something somewhat useful for the end user but
otherwise you should not try to catch each and every exception in
every possible place.
This depends on the application and the situation. If your building a library component, you should bubble up exceptions, although they should be wrapped to be contextual with your component. For example if your building an Xml Database and let's say you are using the file system to store your data, and you are using file system permissions to secure the data. You wouldn't want to bubble up a FileIOAccessDenied exception as that leaks your implementation. Instead you would wrap the exception and throw an AccessDenied error. This is especially true if you distribute the component to third parties.
As for if it's okay to swallow exceptions. That depends on your system. If your application can handle the failure cases and there is no benefit from notifying the user why it failed then go ahead, although I highly recommend that your log the failure. I've always found it frustating being called to help troubleshoot an issue and find they were swallowing the exception (or replacing it and throwing a new one instead without setting the inner exception).
In general I use the following rules:
In my components & libraries I only catch an exception if I intend to handle it or do something based on it. Or if I want to provide additional contextual information in an exception.
I use a general try catch at the application entry point, or the highest level possible. If an exception gets here I just log it and let it fail. Ideally exceptions should never get here.
I find the following code to be a smell:
try
{
//do something
}
catch(Exception)
{
throw;
}
Code like this serves no point and should not be included.
I would like to recommend another good source on the topic. It's an interview with inventors of C# and Java, Anders Hejlsberg and James Gosling respectively, on the topic of Java's Checked Exception.
Failure and Exceptions
There are also great resources at the bottom of the page.
I tend to agree with Anders Hejlsberg and you that the most callers only care if operation is successful or not.
Bill Venners: You mentioned
scalability and versioning concerns
with respect to checked exceptions.
Could you clarify what you mean by
those two issues?
Anders Hejlsberg: Let's start with
versioning, because the issues are
pretty easy to see there. Let's say I
create a method foo that declares it
throws exceptions A, B, and C. In
version two of foo, I want to add a
bunch of features, and now foo might
throw exception D. It is a breaking
change for me to add D to the throws
clause of that method, because
existing caller of that method will
almost certainly not handle that
exception.
Adding a new exception to a throws
clause in a new version breaks client
code. It's like adding a method to an
interface. After you publish an
interface, it is for all practical
purposes immutable, because any
implementation of it might have the
methods that you want to add in the
next version. So you've got to create
a new interface instead. Similarly
with exceptions, you would either have
to create a whole new method called
foo2 that throws more exceptions, or
you would have to catch exception D in
the new foo, and transform the D into
an A, B, or C.
Bill Venners: But aren't you breaking
their code in that case anyway, even
in a language without checked
exceptions? If the new version of foo
is going to throw a new exception that
clients should think about handling,
isn't their code broken just by the
fact that they didn't expect that
exception when they wrote the code?
Anders Hejlsberg: No, because in a lot
of cases, people don't care. They're
not going to handle any of these
exceptions. There's a bottom level
exception handler around their message
loop. That handler is just going to
bring up a dialog that says what went
wrong and continue. The programmers
protect their code by writing try
finally's everywhere, so they'll back
out correctly if an exception occurs,
but they're not actually interested in
handling the exceptions.
The throws clause, at least the way
it's implemented in Java, doesn't
necessarily force you to handle the
exceptions, but if you don't handle
them, it forces you to acknowledge
precisely which exceptions might pass
through. It requires you to either
catch declared exceptions or put them
in your own throws clause. To work
around this requirement, people do
ridiculous things. For example, they
decorate every method with, "throws
Exception." That just completely
defeats the feature, and you just made
the programmer write more gobbledy
gunk. That doesn't help anybody.
EDIT: Added more details on the converstaion
Checked exceptions are a controversial issue in general, and in Java in particular (later on I'll try to find some examples for those in favor and opposed to them).
As rules of thumb, exception handling should be something around these guidelines, in no particular order:
For the sake of maintainability, always log exceptions so that when you start seeing bugs, the log will assist in pointing you to the place your bug has likely started. Never leave printStackTrace() or the likes of it, chances are one of your users will get one of those stack traces eventually, and have exactly zero knowledge as to what to do with it.
Catch exceptions you can handle, and only those, and handle them, don't just throw them up the stack.
Always catch a specific exception class, and generally you should never catch type Exception, you are very likely to swallow otherwise important exceptions.
Never (ever) catch Errors!!, meaning: Never catch Throwables as Errors are subclasses of the latter. Errors are problems you will most likely never be able to handle (e.g. OutOfMemory, or other JVM issues)
Regarding your specific case, make sure that any client calling your method will receive the proper return value. If something fails, a boolean-returning method might return false, but make sure the places you call that method are able to handle that.
You should only catch the exceptions you can deal with. For example, if you're dealing with reading over a network and the connection times out and you get an exception you can try again. However if you're reading over a network and get a IndexOutOfBounds exception, you really can't handle that because you don't (well, in this case you wont) know what caused it. If you're going to return false or -1 or null, make sure it's for specific exceptions. I don't want a library I'm using returning a false on a network read when the exception thrown is the heap is out of memory.
Exceptions are errors that are not part of normal program execution. Depending on what your program does and its uses (i.e. a word processor vs. a heart monitor) you will want to do different things when you encounter an exception. I have worked with code that uses exceptions as part of normal execution and it is definitely a code smell.
Ex.
try
{
sendMessage();
if(message == success)
{
doStuff();
}
else if(message == failed)
{
throw;
}
}
catch(Exception)
{
logAndRecover();
}
This code makes me barf. IMO you should not recover from exceptions unless its a critical program. If your throwing exceptions then bad things are happening.
All of the above seems reasonable, and often your workplace may have a policy. At our place we have defined to types of Exception: SystemException (unchecked) and ApplicationException (checked).
We have agreed that SystemExceptions are unlikely to be recoverable and will bve handled once at the top. To provide further context, our SystemExceptions are exteneded to indicate where they occurred, e.g. RepositoryException, ServiceEception, etc.
ApplicationExceptions could have business meaning like InsufficientFundsException and should be handled by client code.
Witohut a concrete example, it's difficult to comment on your implementation, but I would never use return codes, they're a maintenance issue. You might swallow an Exception, but you need to decide why, and always log the event and stacktrace. Lastly, as your method has no other processing it's fairly redundant (except for encapsulation?), so doactualStuffOnObject(p_jsonObject); could return a boolean!
After some thought and looking at your code it seems to me that you are simply rethrowing the exception as a boolean. You could just let the method pass this exception through (you don't even have to catch it) and deal with it in the caller, since that's the place where it matters. If the exception will cause the caller to retry this function, the caller should be the one catching the exception.
It can at times happen that the exception you are encountering will not make sense to the caller (i.e. it's a network exception), in which case you should wrap it in a domain specific exception.
If on the other hand, the exception signals an unrecoverable error in your program (i.e. the eventual result of this exception will be program termination) I personally like to make that explicit by catching it and throwing a runtime exception.
If you are going to use the code pattern in your example, call it TryDoSomething, and catch only specific exceptions.
Also consider using an Exception Filter when logging exceptions for diagnostic purposes. VB has language support for Exception filters. The link to Greggm's blog has an implementation that can be used from C#. Exception filters have better properties for debuggability over catch and rethrow. Specifically you can log the problem in the filter and let the exception continue to propagate. That method allows an attaching a JIT (Just in Time) debugger to have the full original stack. A rethrow cuts the stack off at the point it was rethrown.
The cases where TryXXXX makes sense are when you are wrapping a third party function that throws in cases that are not truly exceptional, or are simple difficult to test without calling the function. An example would be something like:
// throws NumberNotHexidecimalException
int ParseHexidecimal(string numberToParse);
bool TryParseHexidecimal(string numberToParse, out int parsedInt)
{
try
{
parsedInt = ParseHexidecimal(numberToParse);
return true;
}
catch(NumberNotHexidecimalException ex)
{
parsedInt = 0;
return false;
}
catch(Exception ex)
{
// Implement the error policy for unexpected exceptions:
// log a callstack, assert if a debugger is attached etc.
LogRetailAssert(ex);
// rethrow the exception
// The downside is that a JIT debugger will have the next
// line as the place that threw the exception, rather than
// the original location further down the stack.
throw;
// A better practice is to use an exception filter here.
// see the link to Exception Filter Inject above
// http://code.msdn.microsoft.com/ExceptionFilterInjct
}
}
Whether you use a pattern like TryXXX or not is more of a style question. The question of catching all exceptions and swallowing them is not a style issue. Make sure unexpected exceptions are allowed to propagate!
I suggest taking your cues from the standard library for the language you're using. I can't speak for C#, but let's look at Java.
For example java.lang.reflect.Array has a static set method:
static void set(Object array, int index, Object value);
The C way would be
static int set(Object array, int index, Object value);
... with the return value being a success indicator. But you're not in C world any more.
Once you embrace exceptions, you should find that it makes your code simpler and clearer, by moving your error handling code away from your core logic. Aim to have lots of statements in a single try block.
As others have noted - you should be as specific as possible in the kind of exception you catch.
If you're going to catch an Exception and return false, it should be a very specific exception. You're not doing that, you're catching all of them and returning false. If I get a MyCarIsOnFireException I want to know about it right away! The rest of the Exceptions I might not care about. So you should have a stack of Exception handlers that say "whoa whoa something is wrong here" for some exceptions (rethrow, or catch and rethrow a new exception that explains better what happened) and just return false for others.
If this is a product that you'll be launching you should be logging those exceptions somewhere, it will help you tune things up in the future.
Edit: As to the question of wrapping everything in a try/catch, I think the answer is yes. Exceptions should be so rare in your code that the code in the catch block executes so rarely that it doesn't hit performance at all. An exception should be a state where your state machine broke and doesn't know what to do. At least rethrow an exception that explains what was happening at the time and has the caught exception inside of it. "Exception in method doSomeStuff()" isn't very helpful for anyone who has to figure out why it broke while you're on vacation (or at a new job).
My strategy:
If the original function returned void I change it to return bool. If exception/error occurred return false, if everything was fine return true.
If the function should return something then when exception/error occurred return null, otherwise the returnable item.
Instead of bool a string could be returned containing the description of the error.
In every case before returning anything log the error.
Some excellent answers here. I would like to add, that if you do end up with something like you posted, at least print more than the stack trace. Say what you were doing at the time, and Ex.getMessage(), to give the developer a fighting chance.
try/catch blocks form a second set of logic embedded over the first (main) set, as such they are a great way to pound out unreadable, hard to debug spaghetti code.
Still, used reasonably they work wonders in readability, but you should just follow two simple rules:
use them (sparingly) at the low-level to catch library handling issues, and stream them back into the main logical flow. Most of the error handling we want, should be coming from the code itself, as part of the data itself. Why make special conditions, if the returning data isn't special?
use one big handler at the higher-level to manage any or all of the weird conditions arising in the code that aren't caught at a low-level. Do something useful with the errors (logs, restarts, recoveries, etc).
Other than these two types of error handling, all of the rest of the code in the middle should be free and clear of try/catch code and error objects. That way, it works simply and as expected no matter where you use it, or what you do with it.
Paul.
I may be a little late with the answer but error handling is something that we can always change and evolve along time. If you want to read something more about this subject I wrote a post in my new blog about it. http://taoofdevelopment.wordpress.com
Happy coding.

Categories

Resources