繁体   English   中英

尝试捕获异常

[英]try catch 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块中执行一些有用的操作(例如记录异常),则可以remove try catch块以引发异常或从catch块throw异常。 如果你想从你的方法发送异常消息, 不想抛出异常 ,然后就可以使用字符串变量来保存异常消息调用方法。

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

暂无
暂无

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

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