Nick Prozee
Nick Prozee

Reputation: 2913

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?

Upvotes: 5

Views: 118

Answers (2)

mikeb
mikeb

Reputation: 11267

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

Upvotes: 9

patryk9200
patryk9200

Reputation: 46

You can read about exceptions here: MSDN

Exceptions give you information about ocurred error. You can easly handle and throw them.

Upvotes: -1

Related Questions