在 c# 自定义异常处理的情况下如何进行构造函数调用

本文关键字:何进行 函数调用 情况下 自定义 异常处理 | 更新日期: 2023-09-27 18:34:02

这是我的程序

class Program
{
    static void Main(string[] args)
    {
        throw new UserAlreadyLoggedInException("Hello");
    }
}
public class UserAlreadyLoggedInException : Exception
{
    public UserAlreadyLoggedInException(string message) : base(message)
    {
        Console.WriteLine("Here");
    }    
}

现在,我知道基类构造函数在派生类构造函数之前运行。但是当我运行上面的代码时,输出结果是

     Here
     Unhandled Exception:Testing.UserAlreadyLoggedInException:Hello.

为什么"这里"在未处理之前打印.....?

在 c# 自定义异常处理的情况下如何进行构造函数调用

您首先必须创建异常,然后才能被抛出。

  1. 创建由 new UserAlreadyLoggedInException 发起的异常实例;
  2. 调用UserAlreadyLoggedInException构造函数;
  3. 调用构造函数内部的Console.WriteLine;
  4. 构造函数完成;
  5. 抛出新创建的异常实例;
  6. 不会处理异常,因此应用程序错误处理程序将错误写入控制台。

你为什么不试试这个:

static class Program
{
  static void Main()
  {
    throw new UserAlreadyLoggedInException("Hello");
  }
}

class LoginException : Exception
{
  public LoginException(string message) : base(message)
  {
    Console.WriteLine("least derived class");
  }
}
class UserAlreadyLoggedInException : LoginException
{
  public UserAlreadyLoggedInException(string message) : base(message)
  {
    Console.WriteLine("most derived class");
  }
}

您也可以尝试像这样编写Main方法:

  static void Main()
  {
    var ualie = new UserAlreadyLoggedInException("Hello");
    Console.WriteLine("nothing bad has happened yet; nothing thrown yet");
    throw ualie;
  }

因此,使用 new 关键字构造Exception实例不会"引发"或"引发"异常。为此,您需要throwthrow语句的工作原理是首先计算 throw 关键字后面的表达式。该评估的结果将是对异常实例的引用。计算表达式后,throw"引发"表达式值引用的异常。

您的误解是,一旦要System.Exception的实例构造函数运行,Exception就会"爆炸"。事实并非如此。

如果您添加自己的尝试/捕获,程序流程将变得更加明显。请注意,Exception 的构造函数不会写入任何内容,它只是存储消息字符串供以后使用。

class Program
{
    static void Main(string[] args)
    {
        try
        {
            throw new UserAlreadyLoggedInException("Hello");
        }
        catch (Exception e)
        {
            Console.WriteLine("My handled exception: {0}", e.Message);
        }
    }
}
public class UserAlreadyLoggedInException : Exception
{
    public UserAlreadyLoggedInException(string message) : base(message)
    {
        Console.WriteLine("Here");
    }    
}
异常在

实例化并引发后打印到控制台。

实例化打印"此处",然后运行时捕获它并打印"未处理的异常:"ToString()表示形式。