简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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