0

So, i have a problem with my C# project. Let's say i have a lot of errors in different classes. And i don't want to try & catch them all. How could i catch an exception anywhere, and show a MessageBox with the message of the exception?

Example:

class Program {
    static void Main(string[] args) {
        DifferentFile.Execute();
    }
}

class DifferentFile {
    public static PictureBox blabla = null;

    public static void Execute() {
        blabla.Image = Resources.SomeImage; // Random code with the picturebox
    }
}

This should throw an exception (This is example code so idk but probably). How could i catch all exceptions in the WHOLE application with a MessageBox (System.Windows.Forms) if i have multiple classes.

(Like this)

try {
    // Code
} catch (Exception ex) {
    MessageBox.Show("Exception thrown:\r\n\r\n" + ex.Message); // Or ex.Stacktrace
}

Also, sorry if anything is wrong or if there is like lack of whatever (Confusing). Please just ask.

Flexan
  • 33
  • 5
  • Put the try/catch block in the Main method. – Robert Harvey Jan 03 '21 at 19:39
  • Tried it, but it seems like it doesn't catch anything from the other method. – Flexan Jan 03 '21 at 19:41
  • 1
    [Application.ThreadException](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.threadexception), [AppDomain.UnhandledException](https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.unhandledexception). See the difference in the Docs. – Jimi Jan 03 '21 at 19:42
  • 2
    Does this answer your question? [How can I make something that catches all 'unhandled' exceptions in a WinForms application?](https://stackoverflow.com/questions/5762526/how-can-i-make-something-that-catches-all-unhandled-exceptions-in-a-winforms-a) – S. Walker Jan 03 '21 at 19:43
  • 1
    To add to the two excellent answers above, here's Microsoft documentation on the subject explaining things in more detail: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.setunhandledexceptionmode?view=net-5.0 – Hamed Jan 03 '21 at 19:47
  • Could you please explain how that works exactly? I've tried the code but it still throws exception in VS. – Flexan Jan 03 '21 at 19:52
  • I think the problem is that i have different files. Does the solution only work on the main class? Or everywhere in the application. (Also im using .NET Framework Blank Project to create a form) – Flexan Jan 03 '21 at 19:58
  • In Debug-Mode, Visual Studio stops the application when an exception is thrown, because, well, you're debugging it. You can prevent this from happening deselecting the exceptions that should not stop the execution. Visual Studio prompts you about it each time an exception is raised in the IDE. – Jimi Jan 03 '21 at 20:04

0 Answers0