如何使用Java风格抛出关键字在C#中? [英] How to use Java-style throws keyword in C#?
问题描述
在Java中,<一个href=\"http://download.oracle.com/javase/tutorial/essential/exceptions/declaring.html\"><$c$c>throws$c$c>关键字允许的方法来声明,它不会自行处理异常,而是扔给调用方法。
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.
有没有在C#中类似的关键字/属性?
Is there a similar keyword/attribute in C#?
如果没有相当的,你怎么能完成相同(或类似)的影响?
If there is no equivalent, how can you accomplish the same (or a similar) effect?
推荐答案
在Java中,你必须要么处理异常或标记方法为一体,可以使用抛出$ C $扔C>关键字。
In Java, you must either handle an exception or mark the method as one that may throw it using the throws
keyword.
C#没有这个关键字或等效之一,因为在C#中,如果你不处理异常,它会冒泡,直到捕获或如果不抓住它会终止程序。
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;
}
这篇关于如何使用Java风格抛出关键字在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!