.NET MAUI平台特定代码无法抛出自定义异常并在共享代码捕获
解决.NET MAUI中平台特定代码抛出异常无法在共享代码中捕获的问题
问题分析
你的代码逻辑本身是通顺的:平台特定的MyCalledMethod抛出异常,MyClass构造函数的try-catch块捕获该异常并包装为自定义MyCustomException,最终在MainPage构造函数中捕获自定义异常。出现“Exception Unhandled”提示,大概率是Visual Studio调试器的异常拦截设置导致的——调试器会提前拦截所有抛出的异常,即使后续代码会处理它。
解决方案
1. 调整调试器异常设置
- 打开Visual Studio的异常设置窗口(快捷键:
Ctrl+Alt+E) - 在弹出的窗口中,找到
Common Language Runtime Exceptions,取消勾选它的「抛出」选项(也可仅取消你不想被拦截的特定异常类型) - 调整后调试器不会在异常抛出时立即中断,代码的
try-catch块就能正常处理异常
2. 验证代码异常传播逻辑(可选)
为确认平台异常确实被捕获,可在MyClass构造函数的catch块中添加日志:
public MyClass() { try { MyPrivateMethod(); } catch (Exception ex) { Console.WriteLine($"捕获到平台异常: {ex.Message}"); // 新增日志 throw new MyCustomException("Error initializing MyClass"); } }
运行后若控制台输出平台异常信息,说明捕获逻辑正常,问题完全出自调试器设置。
3. 异步场景下的异常处理(若涉及异步操作)
如果平台特定代码包含异步逻辑,必须使用async/await确保异常能正确传播:
// 共享代码中的MyClass public partial class MyClass { public async Task InitializeAsync() { try { await MyPrivateMethodAsync(); } catch (Exception ex) { throw new MyCustomException("Error initializing MyClass"); } } partial Task MyPrivateMethodAsync(); } // 平台特定代码实现 public partial class MyClass { partial async Task MyPrivateMethodAsync() { await MyCalledMethodAsync(); } async Task MyCalledMethodAsync() { // 异步操作逻辑 throw new Exception("Something went wrong in MyCalledMethod"); } } // MainPage中调用 public MainPage() { InitializeComponent(); Loaded += async (s, e) => { try { _myClass = new MyClass(); await _myClass.InitializeAsync(); } catch (MyCustomException ex) { Console.WriteLine($"Error: {ex.Message}"); } }; }
总结
绝大多数情况下,这类“未处理异常”提示是调试器设置导致的,调整异常设置后即可让代码的捕获逻辑正常工作。若涉及异步场景,务必通过async/await来正确传播异常。
内容的提问来源于stack exchange,提问作者Prabhav Mehra
相关产品推荐
相关产品推荐

