this keywords allows for a method to not handle an exception by its own, but rather throw it to the calling method. If there is no equivalent, how can you accomplish the same (or a similar) effect?
see this to read about java throws keyword / clause
this keywords allows for a method to not handle an exception by its own, but rather throw it to the calling method. If there is no equivalent, how can you accomplish the same (or a similar) effect?
see this to read about java throws keyword / clause
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;
}
You are asking about this :
Re-throwing an Exception
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
or
static void Main()
{
string s = null;
if (s == null)
{
throw new ArgumentNullException();
}
Console.Write("The string s is null"); // not executed
}
Here's an answer to a similar question I just fund on bytes.com:
The short answer is no, there are no checked exceptions in C#. The designer of the language discusses this decision in this interview:
http://www.artima.com/intv/handcuffs.html
The nearest you can get is to use the tags in your XML documentation, and distribute NDoc generated docs with your code/assemblies so that other people can see which exceptions you throw (which is exactly what MS do in the MSDN documentation). You can't rely on the compiler to tell you about unhandled exceptions, however, like you may be used to in java.
Actually not having checked exceptions in C# can be considered a good or bad thing.
I myself consider it to be a good solution since checked exceptions provide you with the following problems:
Because of that in most bigger applications you will see the following pattern often when checked Exceptions occur:
try {
// Some Code
} catch(SomeException ex){
throw new RuntimeException(ex);
}
Which essentially means emulating the way C#/.NET handles all Exceptions.
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...
}