【问题标题】:Where do I catch this simple bug?我在哪里可以捕捉到这个简单的错误?
【发布时间】:2011-03-11 17:09:30
【问题描述】:

以下是相关代码:

公共类User.cs:

public void FindByID(int id)
        {
            Parser parser = new Parser(id);

            ID = parser.FindID();
            Name = parser.FindName();
            Rating = parser.FindRating();
            Photo = parser.FindPhoto();
            Reputation = parser.FindReputation();
            Group = parser.FindGroup();
            PostCount = parser.FindPosts();
            PostPerDay = parser.FindPostsPerDay();
            JoinDate = parser.FindJoinDate();
            Views = parser.FindViews();
            LastActive = parser.FindLastActive();
            Title = parser.FindTitle();
            Age = parser.FindAge();
            Birthday = parser.FindBirthday();
            Sex = parser.FindSex();
        }

公共类Parser.cs:

public Parser(int userID)
        {
            doc = XDocument.Load(String.Format("http://www.dreamincode.net/forums/xml.php?showuser={0}", userID));            
        }

        /***********************************************************
         * Methods that scrape information individually for fields *
         * ********************************************************/

        public string FindID()
        {
            return doc.XPathSelectElement("/ipb/profile/id").Value;
        }

        public string FindName()
        {
            return doc.XPathSelectElement("/ipb/profile/name").Value;
        }

        /etc etc etc

如果我尝试搜索不存在的用户,则会引发异常,因为 doc 从未初始化。我不确定我应该在哪里捕获这个错误。也许我做事的方式让我处于这个位置。

我想学习。 :P 谢谢!

编辑:这是 Stacktrace:

   at DICHeads.Parser.FindID() in c:\users\sergio\documents\visual studio 2010\Projects\DICHeads\DICHeads\Parser.cs:line 36
   at DICHeads.User.FindByID(Int32 id) in c:\users\sergio\documents\visual studio 2010\Projects\DICHeads\DICHeads\User.cs:line 33
   at DICHeads.MainWindow.button1_Click(Object sender, RoutedEventArgs e) in c:\users\sergio\documents\visual studio 2010\Projects\DICHeads\DICHeads\MainWindow.xaml.cs:line 36
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.CrackMouseButtonEventAndReRaiseEvent(DependencyObject sender, MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at DICHeads.App.Main() in c:\users\sergio\documents\visual studio 2010\Projects\DICHeads\DICHeads\obj\x86\Debug\App.g.cs:line 0
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

【问题讨论】:

  • 你能粘贴异常甚至堆栈跟踪吗?像一个关于什么有效和什么无效的小例子也可以帮助我们帮助你:)
  • 例如,ID“1234”有效,但ID“22222222”无效。我将使用实际的错误消息编辑我的问题。
  • 很高兴您发布了堆栈跟踪,但您忘记了最重要的部分:异常类型和消息。它应该在您发布的部分的正上方。我猜这是 NullReferenceException 但很高兴看到它得到确认。
  • 我设法用你的建议解决了这个问题。非常感谢!

标签: c# .net exception null


【解决方案1】:

您的代码可能会抛出 NullReferenceException,因为如果找不到该元素,XPathSelectElement 会返回 null。

返回值
类型:System.Xml.Linq.XElement
一个 XElement,或 null。

将您的代码更改为:

public string FindID()
{ 
    var element = doc.XPathSelectElement("/ipb/profile/id");
    if (element == null) { return null; }
    return element.Value;
}

对于您的其他方法也是如此。

【讨论】:

    【解决方案2】:

    我会怎么做:

    1. 如果用户不存在,则从构造函数中抛出 no-such-user 异常(或类似异常)。
    2. 将构造函数调用包装在 try-catch 块中。

    【讨论】:

      【解决方案3】:

      有两种方法可以处理它。

      1. 您可以添加检查构造函数以查看是否已填充 doc。如果不创建一个新的默认实例,那么您的所有代码仍然可以工作,但不会返回任何结果。虽然一旦在构造函数之外,您可以使用 if 包装以下代码以检查是否确实加载了文档。

      2. 您可以跳过默认实例,只检查构造函数外部的文档,就像在第一个解决方案中一样。

      【讨论】:

        猜你喜欢
        • 2012-03-12
        • 1970-01-01
        • 2019-01-20
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-15
        相关资源
        最近更新 更多