简体   繁体   English

尝试捕获异常

[英]try catch exception

We often use try catch statements in our method, if the method can return a value, but the value doesn't a string, how to return the exception message? 我们经常在方法中使用try catch语句,如果该方法可以返回值,但该值不是字符串,那么如何返回异常消息? For example: 例如:

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

How to return the exception? 如何返回异常?

You can remove try catch block to throw exception or throw exception from catch block if you want to do something useful in catch block like logging the exception. 如果要在catch块中执行一些有用的操作(例如记录异常),则可以remove try catch块以引发异常或从catch块throw异常。 If you want to send exception message from your method and do not want to throw exception then you can use out string variable to hold the exception message for calling method. 如果你想从你的方法发送异常消息, 不想抛出异常 ,然后就可以使用字符串变量来保存异常消息调用方法。

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

How to call the method. 如何调用方法。

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

If you simply want to throw any exception, remove try/catch block. 如果您只想引发任何异常,请删除try / catch块。

If you want to handle specific exceptions you have two options 如果要处理特定的异常,则有两种选择

  1. Handle those exceptions only. 仅处理那些异常。

     try { //... return i; } catch(IOException iex) { // do something throw; } catch(PathTooLongException pex) { // do something throw; } 
  2. In generic handler do something for certain types 在通用处理程序中为某些类型做一些事情

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

you can directly throw your exception, and from calling method or event catch that exception. 您可以直接引发异常,并从调用方法或事件中捕获该异常。

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

and catch that in calling method like this... 并在这样的调用方法中捕获...

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