TrN
TrN

Reputation: 1250

if statement for throwing Exception?

Hi I wanted to ask because I'm not sure if is it propriete using of Exception:

public int Method(int a, int b) {
   if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
   //do stuff... 
}

can I throw Exception after if statement? or should I always use try - catch when it goes with the exceptions?

Upvotes: 24

Views: 49883

Answers (7)

user1451111
user1451111

Reputation: 1943

All above answers are correct but I like to mention one additional point here which I did not see mentioned in any of the answers. The reason why you should throw an exception and not return an integer e.g. 0 or -1 for signalling that an error occurred, is that the returned integer can be mistakenly treated/assumed as a valid result of your method. It is an integer anyway, and your method, after performing its internal logic returns an integer. So the caller of this method can mistakenly treat any returned integer as a valid result, which can lead to bugs down the line. In that case, throwing an exception makes perfect sense.

Upvotes: 0

Mark Staff
Mark Staff

Reputation: 721

You've got the right idea. You could use your code like this:

void MyMainMethod()
{

    // ... oh, let's call my Method with some arguments
    // I'm not sure if it'll work, so best to wrap it in a try catch

    try
    {
        Method(-100, 500);
    }
    catch (ArgumentException ex)
    {
        Console.WriteLine(ex.Message);
    }

}


public int Method(int a, int b)
{
    if (a < b) throw new ArgumentException("the first argument cannot be less than the second");

    //do stuff ...  and return 

}

It might help to look through MSDN's Handling and Throwing Exceptions and Best Practices for Handling Exceptions

Upvotes: 3

crypted
crypted

Reputation: 10306

This is perfectly valid, you can use the same construct even with the constructors. But What you should not do is

   public int Method(int a, int b)
    {
        try
        {
            if (a < b)
                throw new ArgumentException("the first argument cannot be less than the second");
        }
        catch (Exception)
        {

        }
        return 0;

    }

Upvotes: 6

Darren Lewis
Darren Lewis

Reputation: 8488

What you've done here is perfectly Ok.

A common pattern for arg checks is to wrap the check/throw code in a static "Contract" class ensuring you have a consistent approach to exception management when validating input arguments.

Slightly off topic but if using .NET 4.0 you can also look at the new Code Contracts feature for validation of method input and output.

Upvotes: 1

Filip Ekberg
Filip Ekberg

Reputation: 36287

That is perfectly valid. That is exactly what exceptions are used for, to check for "Exceptions" in your logic, things that weren't suppose to be.

The idea behind catching an exception is that when you pass data somewhere and process it, you might not always know if the result will be valid, that is when you want to catch.

Regarding your method, you don't want to catch inside Method but infact when you call it, here's an example:

try
{
    var a = 10;
    var b = 100;
    var result = Method(a, b);
}
catch(ArgumentException ex) 
{
    // Report this back to the user interface in a nice way 
}

In the above case, a is less than b so you can except to get an exception here, and you can handle it accordingly.

Upvotes: 27

dlev
dlev

Reputation: 48596

In this case, you don't want to catch the exception. You're throwing it to alert the caller that they've made a mistake in the way they called your method. Catching it yourself would prevent that from happening. So yes, your code looks fine.

Upvotes: 11

T.J. Crowder
T.J. Crowder

Reputation: 1074148

That's perfectly fine. You're throwing the exception, not catching/handling it, so you wouldn't need a try/catch block for it.

Upvotes: 8

Related Questions