Why are exceptions always accepted as return type (on throw)?

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

Valid Example 1:

public string foo() { return "Hello World!"; } 

Invalid example (obvious):

 public string foo() { return 8080; } 

Valid example 2:

 public string foo() { throw new NotImplementedException("Hello Stackoveflow!"); } 


I see that my " Invalid Example " throws and does not return an exception, however my method never returns the type defined by the method. Why does my compiler allow this to compile?

+5
source share
2 answers

Exceptions are not return types; exceptions indicate an error in the method and that it cannot continue.

Your actual example 2 returns nothing, the compiler knows that it will always throw an exception, so it does not need to worry about returning.

If you have:

 public string foo(int something) { if(something > 10){ throw new NotImplementedException("Hello Stackoveflow!"); } } 

he will complain because you are not returning the value all the time.

Also, from your example, if you had: string val = something() in your code, val will never be set, because the exception is not a return value.

However, this is a valid code, your function can either return a value based on its signature, or throw an exception. Anyway, you can expect warnings from the compiler. I'm not sure about C #, but in java, if you have code that is defined as unreachable, you will get warnings, for example:

 public string foo(int something) { throw new NotImplementedException("Hello Stackoveflow!"); return "OK"; } 

This code will give you a warning because this method cannot reach the return statement (but it is still valid code, at least if it was Java).

+9
source

You can read about exceptions here: MSDN

Exceptions give you information about the error that occurred. You can easily handle and throw them.

-1
source

Source: https://habr.com/ru/post/1236334/


All Articles