Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java-style throws keyword in 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?

like image 665
Louis Rhys Avatar asked Aug 12 '10 07:08

Louis Rhys


People also ask

How do you use a throw keyword?

The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code. The throws keyword is used in a method signature and declares which exceptions can be thrown from a method.

What is Java throw keyword?

The throw keyword is used to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException , ClassNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc.

Does C# have a throws clause?

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.


2 Answers

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... } 
like image 196
serg10 Avatar answered Sep 28 '22 12:09

serg10


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; } 
like image 40
Oded Avatar answered Sep 28 '22 11:09

Oded