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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…