尝试捕获异常

本文关键字:捕获异常 | 更新日期: 2023-09-27 17:50:01

我们经常在方法中使用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块中做一些有用的事情,比如记录异常,你可以remove try catch块抛出异常或throw exception from catch块。如果你想从你的方法中发送异常消息,而不想抛出异常,那么你可以使用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);

如果您只是想抛出任何异常,请删除try/catch块。

如果你想处理特定的异常,你有两个选择

  1. 只处理这些异常

    try
    {
        //...
        return i;
    }
    catch(IOException iex)
    { 
        // do something
       throw;
    }
    catch(PathTooLongException pex)
    { 
        // do something
       throw;
    }
    
  2. 在泛型处理程序中为某些类型做一些事情

    try
    {
        //...
        return i;
    }
    catch(Exception ex)
    { 
         if (ex is IOException) 
         { 
         // do something
         }
         if (ex is PathTooLongException) 
         { 
          // do something 
         }
         throw;
    }
    

你可以直接抛出异常,并通过调用方法或事件捕获该异常。

public int GetFile(string path)
{
        int i;
        try
        {
            //...
            return i;
        }
        catch (Exception ex)
        { 
            throw ex;
        }
}

,然后像这样调用方法…

public void callGetFile()
{
      try
      {
           int result = GetFile("your file path");
      }
      catch(exception ex)
      {
           //Catch your thrown excetion here
      }
}