1

Suppose I need something like this.( This code is blunder, but just an example). This code is not my problem! Its just an example. I know how to write it using if else statements. I'm considering a more complicated Context!

int[] arraynums = new int[3] {1,2,3};
int Sample = 0;
try
{
Sample = arraynums[3];
}
catch
{
Sample=4;
}

Here I can use an alternative logic which wont't run into an error. But still I can reduce the code if I use try catch block. Is it advisable to use a try catch block to solve a logic? If no, then why?

Subin Jacob
  • 4,078
  • 6
  • 32
  • 65

4 Answers4

6

For following reason you should not use exception to implement business logic (or flow control):

  • This is not a good practice. It would confuse the other devs, even you would be confused after 6 month.(This violates the PrincipleOfLeastAstonishment. This makes it harder for programmers to read.)
  • Exception is costly.
  • Bad design.

There are fairly good amount of material available in other posts:

There is whole wiki about it: http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl

Community
  • 1
  • 1
Falaque
  • 856
  • 2
  • 12
  • 26
3

Why not using an if-statement?

if(arraynums.length > 3)
{
    Sample = arraynums[3];
}
else
{
    Sample = 4;
}
Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
  • I know it. but can I use it like that? – Subin Jacob Mar 18 '13 at 04:51
  • 2
    Of course you can use it like that! Why not try it yourself before asking questions like this? – griegs Mar 18 '13 at 04:52
  • Can I use try catch like that?. I knew it could be used like that using if statements. But if I felt that try catch is simpler in a different context, can I use it there to solve the problem? – Subin Jacob Mar 18 '13 at 05:02
  • 3
    @SubinJacob - I think you're confusing **can** and **should**. **can** is on topic for this site, which has been answered, but **should** is off-topic because it'll likely solicit debate. Try http://programmers.stackexchange.com for a discussion on design patterns. – beatgammit Mar 18 '13 at 05:16
3

I'm assuming your code is fairly contrived, since it's pretty easy to rewrite it without an exception. Exceptions are relatively expensive for the run-time. They can needlessly slow down your code if abused. In general, you should check for exceptional conditions before you allow them to be thrown.

Recommended reading:

p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
  • 1
    +1 I hate it when I see code that throws only to unwind the stack. It's usually a sign of bad design. Yes, you technically can do that, but **should** is another issue... – beatgammit Mar 18 '13 at 05:02
0

Personally I would only ever use a try catch for errors or in circumstances where you are not sure whether the object will be available at run time.

In your code you might be better off setting Sample = 4 as a default and doing a check before setting it to arraynums[3].

griegs
  • 22,002
  • 28
  • 113
  • 201