Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are exceptions always accepted as a return type (when thrown)?

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?

like image 521
Nick Prozee Avatar asked Nov 19 '15 13:11

Nick Prozee


People also ask

Can an exception be a return type?

Think of exceptions as a separate return type that gets used only when needed.

Does throwing an exception return the function?

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.

Why is using exceptions a better idea than returning an error value?

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.

What is the point of throwing an exception?

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.


1 Answers

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

like image 105
mikeb Avatar answered Sep 28 '22 06:09

mikeb