Why are exceptions always accepted as a return type (thrown)?
Valid example 1:
public string foo()
{
return "Hello World!";
}
Invalid example (obviously):
public string foo()
{
return 8080;
}
Valid example 2:
public string foo()
{
throw new NotImplementedException("Hello Stackoveflow!");
}
I can see that my "Invalid Example" is 'throwing' and not 'returning' the Exception, however, my method does never return the type defined by the method. How come my compiler allows this to compile?
Think of exceptions as a separate return type that gets used only when needed.
No, because throwing an exception is not a return. If the exception is not handled inside the function it will cause an immediate exit out of the function, passing control to the first point in the program where the exception will be catched ie handled.
Return codes are more brittle The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception. The error won't be ignored.
The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Exceptions are not return types, exceptions indicate an error in the method and that it cannot continue.
Your valid example 2 does not return anything, the compiler knows that it will always throw an exception, so it does not need to worry about returning.
If you had:
public string foo(int something)
{
if(something > 10){
throw new NotImplementedException("Hello Stackoveflow!");
}
}
it would complain, because you are not returning a value all the time.
Also, from your example, if you had: string val = something()
in your code, val would never get set, because an exception is not a return value.
However, it is valid code, your function can either return a value based on its signature or throw an exception. If anything, you might expect a warning by the compiler. I'm not sure about C#, but in java if you have code that is determined to be unreachable you will get warnings, such as:
public string foo(int something)
{
throw new NotImplementedException("Hello Stackoveflow!");
return "OK";
}
This code would give you a warning, because it is impossible for this method to reach the return statement (but it is still valid code, at least if it were Java).
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