简体   繁体   English

在catch块中引发异常

[英]Throwing an exception in catch block

I can't understand how to handle an exception in a method which returns value, in my case the value of Person[] type. 我无法理解如何在返回值的方法中处理异常,在我的情况下,返回值是Person []类型的值。 I tried to do as written here - Creating and Throwing Exceptions , but I'm still getting an exception in - throw icex; 我试图按照这里写的那样- 创建和抛出异常 ,但是我仍然遇到异常-抛出icex; line. 线。 Could someone please give me a hint? 有人可以给我一个提示吗? I also tried to return null in catch block, instead of throw, but I only get another exception.(I'm using ArrayList instead of List intentionally) 我还尝试在catch块中返回null而不是throw,但是我只得到另一个异常(我故意使用ArrayList而不是List)

static ArrayList CreateNonGenericList()
    {            
        ArrayList personList = new ArrayList()
            {
                new Person {FirstName="John", LastName="Clark", Age=39, 
                    StartDate= new DateTime(1989, 12, 30)},
                new Person{FirstName="Zefa", LastName="Thoms", Age=23, 
                    StartDate= new DateTime(2003, 4, 12)},
                new Person{FirstName="Robin", LastName="Hood", Age=33, 
                    StartDate= new DateTime(2001, 4, 12)}
            };
        personList.Add("John"); //Passing a String value instead of Person
        return personList;
    }

    static Person[] SortNonGenericList(ArrayList personList)
    {
        try
        {
            Person[] latestpersonList = (from Person p in personList
                                         where p.StartDate > new DateTime(2000, 1, 1)
                                         select p).ToArray();
            return latestpersonList; 
        }
        catch (InvalidCastException ex)
        {
            InvalidCastException icex = new InvalidCastException(ex.Message, ex);                
            throw icex; //Getting an InvalidCastException here  
        }    
    }        

If all you want to do is let the caller of your method to handle the exception, you can remove the try/catch block entirely. 如果您只想让方法的调用者处理该异常,则可以完全删除try/catch块。 Exceptions will "bubble up" automatically when they are not caught. 如果未捕获到异常,它们将自动“冒泡”。

If you would like to do something in the catch block (such as logging) you should throw the original exception: 如果您想在catch块中执行某些操作(例如日志记录),则应抛出原始异常:

catch (InvalidCastException ex)
{
    // Log(ex);
    throw;
}

This way the stack trace in the exception is not "reset" as in your current code. 这样,异常中的堆栈跟踪不会像当前代码中那样“重置”。

As others have pointed out, what you're currently doing is useless because you're throwing a new exception with the same type and message. 正如其他人指出的那样,您当前正在做的事情是没有用的,因为您正在抛出具有相同类型和消息的异常。 Creating a new exception can be useful though if for instance you want a more descriptive exception: 尽管例如,如果您想要描述性更强的异常,则创建新异常可能会很有用:

catch (InvalidCastException ex)
{
    throw new ApplicationException("Unable to Sort list because at least one person has no StartDate", ex);
}

The exception would then still "occur" in the catch block, but its description would then provide useful information for that location in the code. 然后,该异常仍将在catch块中“发生”,但是其描述将为代码中的该位置提供有用的信息。

Of course in the end you would have to actually handle the exception. 当然,最后您必须实际处理该异常。 What do you want to do if you can't sort the personList? 如果无法对personList排序,该怎么办? Return them in their original order? 以原始顺序归还它们吗? Quit the application? 退出应用程序? Tell the end user that the operation has failed? 告诉最终用户操作失败?

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

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