2

I am new to C#. I am getting this exception at the end of my program:

An unhandled exception of type 'System.ArithmeticException' occurred in mscorlib.dll

Additional information: Overflow or underflow in the arithmetic operation.

If there is a handler for this exception, the program may be safely continued.

Line where this exception is thrown really doesn't seem to be related to any arithmetical operations - actually I think that is the last line of my program, e.g., when it tries to exist.

I really have no idea what went wrong. Is there a way I can defeat this issue?

ps. call stack:

>   mscorlib.dll!double.IsPositiveInfinity(double d) + 0xc bytes    
    PresentationFramework.dll!System.Windows.Window.ValidateTopLeft(double length) + 0x25 bytes 
    PresentationFramework.dll!System.Windows.Window.CoerceTop(System.Windows.DependencyObject d, object value) + 0x64 bytes 
    WindowsBase.dll!System.Windows.DependencyObject.ProcessCoerceValue(System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata metadata, ref System.Windows.EntryIndex entryIndex, ref int targetIndex, ref System.Windows.EffectiveValueEntry newEntry, ref System.Windows.EffectiveValueEntry oldEntry, ref object oldValue, object baseValue, object controlValue, System.Windows.CoerceValueCallback coerceValueCallback, bool coerceWithDeferredReference, bool coerceWithCurrentValue, bool skipBaseValueChecks) + 0x55 bytes   
    WindowsBase.dll!System.Windows.DependencyObject.UpdateEffectiveValue(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata metadata, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType) + 0x247 bytes   
    WindowsBase.dll!System.Windows.DependencyObject.CoerceValue(System.Windows.DependencyProperty dp) + 0xd5 bytes  
    PresentationFramework.dll!System.Windows.Window.SetupInitialState(double requestedTop, double requestedLeft, double requestedWidth, double requestedHeight) + 0x135 bytes   
    PresentationFramework.dll!System.Windows.Window.CreateSourceWindow(bool duringShow) + 0x30b bytes   
    PresentationFramework.dll!System.Windows.Window.CreateSourceWindowDuringShow() + 0xa bytes  
    PresentationFramework.dll!System.Windows.Window.SafeCreateWindowDuringShow() + 0x3f bytes   
    PresentationFramework.dll!System.Windows.Window.ShowHelper(object booleanBox) + 0x77 bytes  
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x56 bytes 
    WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) + 0x3a bytes    
    WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl() + 0xac bytes  
    WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object state) + 0x38 bytes 
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0xa7 bytes  
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x16 bytes  
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x41 bytes    
    WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke() + 0x5b bytes  
    WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() + 0x16b bytes    
    WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x5a bytes 
    WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x9b bytes    
    WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) + 0x6b bytes    
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x56 bytes 
    WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) + 0x3a bytes    
    WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) + 0x10e bytes 
    WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) + 0xf1 bytes 
    [Native to Managed Transition]  
    [Managed to Native Transition]  
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0xae bytes  
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes  
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4b bytes  
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes  
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes 
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes 
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes 
    CardReaderGui.exe!CardReaderGui.App.Main() + 0x59 bytes C#
    [Native to Managed Transition]  
    [Managed to Native Transition]  
    mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x6b bytes    
    Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x27 bytes  
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x6f bytes   
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0xa7 bytes  
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x16 bytes  
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x41 bytes    
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes   
    [Native to Managed Transition]  
  • 4
    Post your code, or we won't be able to help. – Bobson May 02 '14 at 14:23
  • @Bobson: I see but that's the problem, project is pretty big and of course I can't post whole project here, and I have no clue in which part of code things maybe going wrong :/ –  May 02 '14 at 14:25
  • ... how are we supposed to know where it's happening if you haven't even tried to find the section causing the problem? – eddie_cat May 02 '14 at 14:26
  • Well, you're in a better position to figure it out than we are. Start commenting things out until it stops throwing errors. Then investigate that section. – Bobson May 02 '14 at 14:27
  • 4
    You can set VS to break when the exception occurs. Debug -> Exceptions, then select the one under Common Language Runtime Exceptions -> System -> System.ArithmeticException. Then you can post the stack trace & code related to the stack trace when it breaks. – Josh May 02 '14 at 14:28
  • 1
    @Josh: Please see my question for stack trace (if I copied it correctly). Also how can I find code related to stack trace??? –  May 02 '14 at 14:38
  • 1
    Are you using WPF? Looks related to this: http://stackoverflow.com/questions/2407040/overflow-or-underflow-in-the-arithmetic-operation-wpf-specific-issue – Josh May 02 '14 at 14:47
  • @Josh: Thanks but doesn't seem to help :( (Yes WPF, I also tried using different dlls as in the answer you linked e.g., msvcr71.dll, etc.) –  May 02 '14 at 15:09

3 Answers3

11

This is a "vexing exception", how can a method that checks for Infinity cause an overflow? There of course is no possible floating point value bigger than Infinity. Only Buzz Lightyear can go to infinity and beyond. Do note that you are not writing a Windows Forms app, the stack trace shows WPF code, very relevant to this kind of problem.

What you are dealing with here is a hardware exception. An exception that was raised by the floating point processor. Such an exception is trapped by the CLR and is re-raised as a managed exception, A System.ArithmeticException.

This is not supposed to happen when you run managed code. It however can happen if the floating point processor is not operating in a mode that's compatible with managed code. In particular, the exception masks in the floating point unit control word were changed from their expected value. This is very likely to cause trouble in a WPF app, it likes using NaN for window coordinates.

This is caused by unmanaged code that ran in your process. Most likely code that uses the Borland C runtime library, a well-known troublemaker. You will need to find that code and eliminate it. Not easy if you don't have a good insight in what's getting used in your program. And can be hard to find if such code is getting injected into your process, such as a shell extension handler that gets loaded when you use one of the shell dialogs, like OpenFileDialog.

Enabling unmanaged debugging and the Debugger + Windows + Modules window is important to get a first lead. Make sure you can account for every DLL you see in that window, paying particular attention to DLLs that do not have a Microsoft copyright notice. SysInternals' Process Monitor can be helpful too. Good luck hunting the snark.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Borland runtime was the culprit for me, as soon as I bypassed it WPF was happy with my window coordinate, otherwise it was throwing this exception for valid coordinates. – click2install Sep 22 '17 at 04:27
  • Wisely analyzed, Hans! Thank's alot. Having a similar trouble here. I tried to open a WPF Window via C++/CLI Bridge-DLL from a Borland/Codegear C++ Builder 2007 Application. I can avoid the exception by calling _controlfp(0x9001F, 0xFFFFF) in the .NET world but I have no clue where exactly the problem is. – Lumo Nov 05 '21 at 16:22
0

In addition to Hans Passant's very instructive answer, I found a relatively simple solution that worked for me. I got a very similar error, which only occurred on about one in 5 computers. Re-installing a Visual C++ Redistributable for Visual Studio 2012 Update 4 solved the issue.

Note that this also worked on computers that did not have Visual Studio installed.

Yellow
  • 3,955
  • 6
  • 45
  • 74
0

I'm know is so late for comment this question, but my case I got this error working with a database context in a service as an attribute of this service for example

  public class XService : System.IDisposable
        {
         private SiactDbContext db = new SiactDbContext();
    }

 public long SaveObject (TypeX object) //In this method the error
        {
            long result = -1;
           
            try
            {
                db.TypeX.Add(object);
                db.SaveChanges();
                result =  retencion.id;
            }
            catch (Exception e)
            {
                Log.Error("Error to saving object");
                Log.Error(e.InnerException.Message);
                Log.Error(e.StackTrace);

            }
       
            return result;
        }

After I used a dbContext private in the method, open and dispose and it worked.

Like that

public long SaveObject (TypeX object)
        {
            long result = -1;
            SiactDbContext db1 = new SiactDbContext();

            try
            {
                db1.TypeX.Add(object);
                db1.SaveChanges();
                result =  object.id;
            }
            catch (Exception e)
            {
                Log.Error("Error to saving object");
                Log.Error(e.InnerException.Message);
                Log.Error(e.StackTrace);

            }
            db1.Dispose();

            return result;
        }
Aly González
  • 51
  • 2
  • 6
  • perhaps add a `finally` to your try/catch and put the dispose in there https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally – Mark Schultheiss Jul 16 '21 at 22:27
  • 1
    Just for me to know: why don't you log e.ToString() instead of InnerException.message with StackTrace? AFAIK e.ToString() prints all Exception Messages and the call stack :) – Lumo Nov 05 '21 at 16:27