How to create mandatory exceptions in C #?


Is there any way to make a method throw an exception that should be handled when the method is invoked?

I used throw new Exception("mensagem de erro") but the treatment is still optional when invoking the method.

asked by anonymous 06.08.2015 / 02:33

3 answers


Fortunately it does not. This is what you want is called a checked exception and you have a number of issues that are not relevant here. In addition to what if there were people would abuse. Is not it enough that people think they should cast and capture Exception ?

The form used is to document and pray. But you can create a static analysis tool that checks this in code. With the new .Net Compiler Platform making it a lot easier and easier to integrate with Visual Studio. It is not so simple, it depends on the programmer to use the tool but it helps.

Creating tests helps a lot. Visual Studio can automatically create many tests for you through Smart Unit Tests, including tests that generate exceptions to see if you've taken care of everything. It's a solution for anyone who programs this way.

An important detail is that situations where this really is necessary are relatively rare. In general, the methods should be able to work regardless of whether the exception is caught or broken.

06.08.2015 / 02:46

Unlike Java, no, this is not possible.

Read a little to read about the reasons for this:

The Trouble with Checked Exceptions

06.08.2015 / 02:46

This is something of the Java copier, which forces certain exceptions to be handled. This is declared in the method signature with the throws statement, as shown below:

public void drinkCoffee(CoffeeCup cup) throws
        TooColdException, TooHotException {
        int temperature = cup.getTemperature();
        if (temperature <= tooCold) {
            throw new TooColdException();
        else if (temperature >= tooHot) {
            throw new TooHotException();

Well, C # does not force you to handle exceptions. But when you program, it's easy to imagine things that can lead to exceptions. And they should always be dealt with, especially if you are developing a more commercial solution that will go into production, or something geared towards general users.

Remember that handling exceptions and minimizing them to the maximum is a good programming practice, even though the language makes this optional. When you do this, you make your code more secure and you will avoid various issues with customer complaints in the future.

06.08.2015 / 02:57