Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c# - System.CommandLine , exceptions are never caught

we are using the following piece of code which uses the system.commandline nuget pkg, the problem that we are seeing is that any exception that happens in the cmd.Invoke(args) is not being caught in the catch block, and the finally statement is being executed, what is required to ensure that the exception is caught so that we can exit properly.

using System;
using System.CommandLine;
using System.CommandLine.Invocation;

namespace cmdarguments
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var cmd = new RootCommand
                {
                    // new Argument<string>("name", "Your name."),
                    new Option<string?>("--optionOne", "The greeting to use."),
                    new Option<string?>("--optionTwo", "The greeting to use."),
                    new Option("--verbose", "Show the deets."),
                };

                cmd.Handler = CommandHandler.Create<string?, string?, bool, IConsole>(HandleGreeting);
                cmd.Invoke(args);

            }

            catch (System.Reflection.TargetInvocationException ex)
            {
                Console.WriteLine(ex);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("Program exited");
            }
        }
        static void HandleGreeting(string? optionOne, string? optionTwo, bool verbose, IConsole console)
        {
            throw new Exception("hello");
            Console.WriteLine(optionOne + optionTwo);
        }

      
    }
}

question from:https://stackoverflow.com/questions/65951137/system-commandline-exceptions-are-never-caught

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...