我有一个自定义的Exception类,我正试图从我的平台特定的.NET MAUI实现中抛出它。我想在MainPage.xaml.cs中捕获这个异常,在这里对象被初始化。
// Exception class
public class MyCustomException : Exception
{
public MyCustomException(string message) : base(message) { }
}
// MyClass partial class in MainCode/Common code
public partial class MyClass
{
public MyClass()
{
try
{
MyPrivateMethod();
}
catch (Exception ex)
{
throw new MyCustomException("Error initializing MyClass");
}
}
partial void MyPrivateMethod();
partial void MyCalledMethod();
}
// Platform-specific implementation of MyClass partial class for .NET MAUI
public partial class MyClass
{
partial void MyPrivateMethod()
{
MyCalledMethod(); // Call the platform-specific implementation of MyCalledMethod
}
partial void MyCalledMethod()
{
// Implement the platform-specific code for MyCalledMethod
// This method can throw an exception
throw new Exception("Something went wrong in MyCalledMethod");
}
}
// Usage in MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private MyClass _myClass;
public MainPage()
{
InitializeComponent();
try
{
_myClass = new MyClass();
}
catch (MyCustomException ex)
{
// Handle the exception here
Console.WriteLine($"Error: {ex.Message}");
}
}
}
我在特定于平台的代码中的MyCalledMethod处获得异常未处理的错误。我想在MainPage.xaml.cs中处理MyCustomException并相应地工作。
1条答案
按热度按时间py49o6xq1#
首先尝试修复MyCustomException构造函数,我看到您正在使用两个参数,并且只定义了一个。修复: