C# explicitly defining what exceptions are thrown

前端 未结 6 559
礼貌的吻别
礼貌的吻别 2020-12-03 09:55

In Java, you explicitly define what exceptions are thrown using the \"throws\" keyword. That way, anyone calling your method knows what to catch.

Is there something

相关标签:
6条回答
  • 2020-12-03 10:30

    As far as I'm aware there is no throws declaration in C# you can document your method indicating that it throws an exception but no forced error handling.

    0 讨论(0)
  • 2020-12-03 10:33

    C# doesn't support checked exceptions. The language designers consider checked exceptions in the way java uses them a bad idea.

    Some workarounds

    0 讨论(0)
  • 2020-12-03 10:35

    C# does not support this. (Not that I know anyway). What you can do is use Xml Comments so that while calling you methods this data will be shown by intellisense.

    0 讨论(0)
  • 2020-12-03 10:36

    There is nothing equivalent in C#: The Trouble with Checked Exceptions

    Other than documentation, there is no way to declare an interface to say "methodX() should throw this exception on error".

    0 讨论(0)
  • 2020-12-03 10:41

    C#/.net does not have checked Exceptions, they proved to be less useful in large scale systems than first thought. In a lot of projects the time to maintain the check exception specs was a lot greater than the debugging time saved by having them.

    Checked Exceptions seem like a good ideal until you have methods that can take delegates or calls into object you pass in. Take a simple case, the Sort() method on a list can’t know what exceptions it will throw, as it does not know what exceptions the Compar() method on the objects being sorted will throw.

    So the spec for the exceptions a method may throw must be able to include information on how exceptions are populated from pass in objects and delegates. No one knows how to do this!

    However there are tools that you check if you are catching all exceptions – see Exception Hunter by Red Gate. I personally don’t see much value in these tool, however if you like checked exceptions you may find them useful.

    0 讨论(0)
  • 2020-12-03 10:54

    This feature is not available in C#. You can make proper XML documentation (3 slashes ///) and state what exceptions are being thrown.

    This will be picked up by the IntelliSense mechanism and will be visible for the users of the class/method before they use it.

    0 讨论(0)
提交回复
热议问题