c# - try catch 异常

标签 c# .net exception

我们经常在方法中使用try catch语句,如果方法可以返回一个值,但该值不是字符串,如何返回异常消息? 例如:

public int GetFile(string path)
{
    int i;
    try
    {
        //...
        return i;
    }
    catch (Exception ex)
    { 
        // How to return the ex?
        // If the return type is a custom class, how to deal with it?
    }
 }

如何返回异常?

最佳答案

如果您想在 catch block 中执行一些有用的操作(例如记录异常),则可以删除 try catch block 以引发异常,或者从 catch block 中抛出异常。如果您想从您的方法发送异常消息并且不想抛出异常,那么您可以使用 out 字符串变量,用于保存调用方法的异常消息。

public int GetFile(string path, out string error)
{
    error = string.Empty.
    int i;
    try
    {
        //...
        return i;
    }
    catch(Exception ex)
    { 
        error = ex.Message;
        // How to return the ex?
        // If the return type is a custom class, how to deal with it?
    }
 }

如何调用该方法。

string error = string.Empty;
GetFile("yourpath", out error);

关于c# - try catch 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064785/

相关文章:

c# - 在运行时更改 CSS 中的值(特别是 .Net)

c# - 区分 Excel Interop 操作引发的异常

java - 在java中捕获异常以使应用程序继续执行

java.lang.ExceptionInInitializerError 由 : java. lang.NullPointerException 引起

c# - 如何正确转义资源文件中的特殊字符?

c# - 在多个线程上运行 COM 组件控件

c# - 在单个 FormView C# 中实现不同的字体样式

c# - 在条件语句中使用 null 条件运算符时,如何处理 null 情况?

c# - 在 DWM 玻璃下使用 TextBox 进行测试

.net - 从数据库行创建对象