gpt4 book ai didi

c# - 异常和返回语句是 C# 中唯一可能的提前退出吗?

转载 作者:IT王子 更新时间:2023-10-29 04:44:18 26 4
gpt4 key购买 nike

例如,我很好奇如果在下面的代码中,我可以确定 Foo()Bar() 将被执行。

try {
... // Assume there is no return statement here
Foo();
} catch (Exception e) {
Bar();
}

我对 finally block 非常熟悉,不需要解释该功能。

我问是因为上面的代码不能在 Java 中工作,因为 Throwable 的存在,这是我通过艰难的方式发现的。

最佳答案

还有停止应用程序的“烧毁房屋”方法:

Environment.Exit(int code);
Environment.FailFast(string message);
Thread.CurrentThread.Abort();
AppDomain.Unload(AppDomain.CurrentDomain);

为了好玩,这里还有一个:)

[DllImport("kernel32.dll",SetLastError = true)]
static extern bool WriteProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte [] lpBuffer,
uint nSize,
out UIntPtr lpNumberOfBytesWritten);

var myProcess = Process.GetCurrentProcess();
var hProcess = myProcess.Handle;
var rnd = new Random();
while(true)
{
var writeTo = new IntPtr((int)rnd.Next(0, int.MaxValue));
var toWrite = new byte[1024];
UIntPtr written;
WriteProcessMemory(
hProcess,
writeTo,
toWrite,
(uint)toWrite.Length,
out written);
}

出于好奇和刺激,让我们试驾一下吧!

我们的测试平台:

    static void Main(string[] args)
{
Trace.Listeners.Add(new ConsoleTraceListener());
AppDomain.CurrentDomain.UnhandledException += OnNoes;
try
{
// INSERT BURN STATEMENT
Foo();
}
catch (Exception e)
{
Bar();
}
finally
{
Baz();
}
}

static void Foo()
{
Trace.WriteLine("I AM FOO!");
}
static void Bar()
{
Trace.WriteLine("I AM BAR!");
}
static void Baz()
{
Trace.WriteLine("I AM BAZ!");
}
static void OnNoes(object sender, UnhandledExceptionEventArgs e)
{
Trace.WriteLine("OhNoes!");
}

结果!

燃烧声明:

Thread.CurrentThread.Abort();

输出:

I AM BAR!
I AM BAZ!

燃烧声明:

AppDomain.Unload(AppDomain.CurrentDomain);

输出:

I AM BAR!
I AM BAZ!

燃烧声明:

Environment.Exit(-1);

输出:

Nothing! No trace output at all!

燃烧声明:

Environment.FailFast("Burn!!!");

输出:

Application crash! A FatalExecutionEngineError was thrown, 
which was not caught by any block/handler. No trace output.

就这样吧!什么?我错过了一个?

燃烧声明:

Splode();

“Splode”在哪里:

    static void Splode()
{
var myProcess = Process.GetCurrentProcess();
var hProcess = myProcess.Handle;
var rnd = new Random();
while (true)
{
var writeTo = new IntPtr((int)rnd.Next(0, int.MaxValue));
var toWrite = new byte[1024];
UIntPtr written;
WriteProcessMemory(
hProcess,
writeTo,
toWrite,
(uint)toWrite.Length,
out written);
}
}

输出:

Application crash! A FatalExecutionEngineError was thrown, 
which was not caught by any block/handler. No trace output.
Crashed Visual Studio while running attached!

关于c# - 异常和返回语句是 C# 中唯一可能的提前退出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15259428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com