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

Louis Rhys picture Louis Rhys · Aug 12, 2010 · Viewed 64.9k times · Source

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?

Answer

serg10 picture serg10 · Aug 12, 2010

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