You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C#程序控制台仅显示自定义异常消息而非堆栈信息?

How to Show Only Custom Exception Message (Not Full Stack Trace) in C# Console

Got it, let's walk through the practical ways you can make your console output just that clean error message instead of the full stack trace dump. Here are a few straightforward options based on your code structure:

1. Catch Exceptions and Print Only the Message Property

The simplest fix is to explicitly catch your custom exception and output only its Message property—instead of printing the entire exception object, which triggers the full stack trace by default.

try
{
    // Your code that calls the Add method, e.g.:
    studentService.Add(new Student { Id = 1 });
}
catch (YourCustomDuplicateException ex) // Replace with your actual custom exception type
{
    Console.WriteLine(ex.Message); // This will only print "Student whit id:1 already exists!"
}

Pro tip: Make sure you're catching your specific custom exception (not just the generic Exception) if you've defined one—this keeps your error handling precise and avoids catching unrelated exceptions by accident.

2. Override ToString() in Your Custom Exception

If you prefer to keep using Console.WriteLine(ex) but still want only the message, you can override the ToString() method in your custom exception class. This changes what gets output when you print the exception directly.

public class YourCustomDuplicateException : Exception
{
    public YourCustomDuplicateException(string message) : base(message) { }

    // Override to return only the message instead of full stack trace
    public override string ToString()
    {
        return Message;
    }
}

Now whenever you print the exception object, it'll just spit out your custom error text, no stack trace included.

3. Handle Uncaught Exceptions Globally

If the exception is uncaught (causing your program to terminate and dump the stack trace automatically), you can set up a global exception handler to intercept it and print only the message:

static void Main(string[] args)
{
    // Hook into the unhandled exception event
    AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
    {
        if (eventArgs.ExceptionObject is Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        // Optional: Exit the program gracefully
        Environment.Exit(1);
    };

    // Rest of your program logic here
}

This ensures even uncaught exceptions won't flood the console with stack trace details.

内容的提问来源于stack exchange,提问作者Teodor Teo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:09:53