Search code examples
c#exceptionhandlerthrow

Throw exception from ClassLibrary


When you try to throw a new exception from ClassLibrary to another project, Visual studio will open Class1.cs and handle the error.

My question is: How can I throw the exception from the called function(ClassLibrary) to the Caller Function(Windows Form)?

Note : I don't want to throw an original exception , i want to throw a custom exception like this

throw new Exception("change your password")

Solution

  • I think you have a long long way to go in your basic understanding of Exceptions and Exception handling, I would highly encourage you to pick up a resource on C# development.

    To solve your immediate issue, I think the answer you are looking for lies in:

    Visual Studio Toolbar->Debug->Exceptions

    Visual studio will "break" on various exceptions that you specify, and anything not checked will simply run through the course of whatever try/catch block handles that type of exception.

    When you mention:

    Note : I don't want to throw an original exception , i want to throw a custom exception like this

    throw new Exception("change your password")
    

    That is the definition of a generic exception, not a custom exception. To define a custom exception, you should subclass Exception:

    public class MyCustomException : Exception 
    {
       ...
    }
    

    and then throw it as such:

    throw new MyCustomException("Some description of what went wrong");
    

    Then, to get Visual Studio to "break" on that specific exception, find your exception in Toolbar->Debug->Exceptions window (under CLR exceptions) and mark the checkbox next to it.