How to use Java-style throws keyword in 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;
}
Is there a throws keyword in C# like in Java?
No, because there are no checked exceptions in C#
If you are trying to document exceptions that are thrown, use the standard xml documentation
/// <exception cref="InvalidOperationException">Why it's thrown.</exception>
Throwing an exception in c#
Noop. You just have to catch
and throw
. Or wrap it into a new exception and throw
.
public void saveToFile(string fileName)
{
try
{
// your code
}
catch(Exception ex)
{
throw;
//or: throw new Exception("Whoops", ex);
}
}
Why do you have to write throws exception in a class definition?
You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception
(an exception that is a subclass of Exception
and not a subclass of RuntimeException
). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.
To answer your two specific questions:
- do you have to write it/what if you don't: if your method throws a checked exception, then yes, you have to declare it in your method signature. If you don't, then your code won't compile.
- do you have to catch it: you have to do something with it. The code calling the method can either catch it and handle it, it can catch it and re-throw it, or it can just pass it up the chain. In order to pass it up the chain, the code calling the method has to itself declare that it throws the same exception -- e.g., if method
bar
can throwSomeException
, and methodfoo
callsbar
and doesn't want to catch the exception, the method signature forfoo
would declare that it too throwsSomeException
.
The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.
How to know if some method can throw an exception
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.
Exception handling in .NET vs Java
The only difference is that Java has some checked exceptions, but C# doesn't.
Since the code you are porting was originally written in Java and assuming it had correct exception handling (a matter that should be fairly language agnostic), then just catch the exceptions in the C# code at the same place where the Java code catches them.
In the absence of signature-level exception clauses, the standard .NET practice for communicating possible exceptions to the user of an API is to simply document them. You can document them in the assembly documentation and in the web documentation (if applicable).
Async method throws exception instantly but is swallowed when async keyword is removed
I thought async methods run synchronously until reaching a blocking method.
They do, but they're still aware that they're executing within an asynchronous method.
If you throw an exception directly from an async void method, the async mechanism is aware that you'd have no way of observing that exception - it won't be thrown back to the caller, because exceptions thrown in async methods are only propagated through tasks. (The returned task becomes faulted.) It would be odd for an exception thrown before the first blocking await
expression to be thrown directly, but exceptions afterwards to be handled differently.
As far as I'm aware, an exception thrown by an async void
method is passed directly to the synchronization context, if there is one. (A continuation is posted to the synchronization context that just throws the exception.) In a simple console app, there isn't a synchronization context, so instead it's thrown as an unreported exception.
If you change your void
method to return Task
, then instead you'll just have an exception which could have been observed, but isn't (because you're not using the return value in TestExAsync
).
Does that make any sense? Let me know if you'd like more clarification - it's all a bit tortuous (and I don't know how well documented it is).
EDIT: I've found a bit of documentation, in the C# 5 spec section 10.15.2:
If the return type of the async function is void, evaluation differs from the above in the following way: Because no task is returned, the function instead communicates completion and exceptions to the current thread's synchronization context. The exact definition of synchronization context is implementation-dependent, but is a representation of "where" the current thread is running. The synchronization context is notified when evaluation of a void-returning async function commences, completes successfully, or causes an uncaught exception to be thrown.
Related Topics
Is There a C# Case Insensitive Equals Operator
What Are the Definitions for Lparam and Wparam
Bundling Not Working in MVC5 When I Turn on Release Mode
Webexception How to Get Whole Response with a Body
What Is the Connection String for Localdb for Version 11
Why Aren't C# Static Class Extension Methods Supported
Passing an Empty Array as Default Value of an Optional Parameter
Drawing Glitches When Using Creategraphics Rather Than Paint Event Handler for Custom Drawing
Task Continuation on UI Thread
Set Custom Path to Referenced Dll'S
Log4Net Rolling Daily Filename with Date in the File Name
Passing a Vector/Array from Unmanaged C++ to C#
Publishing a Website Is Not Updating My CSS Bundles
What's the Difference Between System.Type and System.Runtimetype in C#
Standardoutput.Readtoend() Hangs