简体   繁体   English

如何在C#中显式引发异常?

[英]How do i throw an exception explicitly in c#?

In Java i can explicitly specify that a method throws an exception like: 在Java中,我可以明确指定方法抛出异常,例如:

public void read() throws IOException{}

What is the c# equivalent of this? C#等效于什么?

What are the best practices for throwing custom exceptions? 引发自定义异常的最佳实践是什么?

I have made them serializable and provided a streaming context also . 我已经使它们可序列化,并且还提供了流上下文。

What you're referring to is the actual documentation of code that throws exceptions. 您所指的是引发异常的代码的实际文档

Read this thread that discusses this question: How to document thrown exceptions 阅读讨论此问题的线程: 如何记录抛出的异常

The topic in MSDN called Exceptions and Exception Handling covers Creating and Throwing Exceptions in detail. MSDN中名为“ 异常和异常处理 ”的主题详细介绍了“ 创建和引发异常”

However, exception specifications are not part of the C# language like they are in Java. 但是,异常规范不是Java中的C#语言的一部分。 You must rely on documentation to tell the user of your API what exceptions may be thrown. 您必须依靠文档来告诉您的API用户可能会抛出哪些异常。 You cannot force a user to handle an exception, or document it in code. 您不能强制用户处理异常或将异常记录在代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM