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?
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.
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.
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.
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... }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With