How to use Java-style throws keyword in C#?

前端 未结 10 2180
说谎
说谎 2020-11-27 04:39

In Java, the throws keyword allows for a method to declare that it will not handle an exception on its own, but rather throw it to the calling method.

Is there a sim

10条回答
  •  清歌不尽
    2020-11-27 05:28

    In Java, you must either handle an exception or mark the method as one that may throw it using the throws keyword.

    C# does not have this keyword or an equivalent one, as in C#, if you don't handle an exception, it will bubble up, until caught or if not caught it will terminate the program.

    If you want to handle it then re-throw you can do the following:

    try
    {
      // code that throws an exception
    }
    catch(ArgumentNullException ex)
    {
      // code that handles the exception
      throw;
    }
    

提交回复
热议问题