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;
}

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...
}

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);
    }