如何在C#中使用Java风格的throws关键字? [英] How to use Java-style throws keyword in C#?

查看:132
本文介绍了如何在C#中使用Java风格的throws关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中, throws 关键字允许一个方法来声明它不会自己处理一个异常,而是把它抛到调用方法。

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中,您必须处理异常或将该方法标记为可以使用 throws 关键字。

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;
}

这篇关于如何在C#中使用Java风格的throws关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆