Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does it not allowed to use try-catch statement without {}?

Tags:

c#

Why can't I use code like this ?

1

int i = 0;

try i = int.Parse("qwerty");
catch throw;

2

try i = int.Parse("qwerty");
catch;
finally Log.Write("error");

And should write like this

1

int i = 0;

try { i = int.Parse("qwerty"); } catch { throw; }

2

try { i = int.Parse("qwerty");}
catch {}
finally {Log.Write("error");}

PS:

I can use if-else statement without {}. Why should I use them with try-catch(-finally) statement ? Is there any meaningful reason ?

Is it only because that some people think that code is hard to read ?

Several months ago I asked that question on russian programming forum but I got no satisfactory answer ...

like image 334
Александр Д. Avatar asked May 06 '10 13:05

Александр Д.


People also ask

Can we use try catch without throw?

Yes it does not have throw or rethrow activity. I put the try catch in the processing part. Then I would recommend you to put a debugger inside catch and see which activity or segment is throwing the exception.

Can we use catch () without passing arguments in it?

You can also omit the arguments on the catch block entirely. In this case, the catch block will catch all exceptions, regardless of their type. Because you don't declare an exception variable, however, you won't have access to information about the exception.

Can you use try without catch JS?

If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead. You can also use the try statement to handle JavaScript exceptions.

Why you should not use try catch?

With a try catch, you can handle an exception that may include logging, retrying failing code, or gracefully terminating the application. Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead.


2 Answers

That's what the language designers decided.

In either case, even a single line if is dangerous - people add lines expecting them to be included in the if, which of course, as they are not in {}, they are not.

like image 91
Oded Avatar answered Oct 21 '22 05:10

Oded


C# probably made the braces a requirement because C++ did. My guess as to why they're required in C++ is that it makes it easier to write nested and multiple catch blocks without making mistakes. The braces add an extra level of scope, which can be convenient, but I can't think of a reason why it would be required.

like image 21
Bill the Lizard Avatar answered Oct 21 '22 04:10

Bill the Lizard