How to use Java-style throws keyword in C#?
C#JavaException HandlingThrowsC# Problem Overview
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?
C# Solutions
Solution 1 - C#
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...
}
Solution 2 - C#
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;
}
Solution 3 - C#
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);
}
Solution 4 - C#
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
Solution 5 - C#
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.
Solution 6 - C#
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
}
Solution 7 - C#
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.
Solution 8 - C#
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. Javathrows
provides an indication of which exceptions could be thrown (i.e. IMO the focus in .Net is inside the method which contracts to prove thethrow
, 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.
Solution 9 - C#
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;
}
Solution 10 - C#
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;
}