O
O
OlegTar2016-11-07 20:48:01
Algorithms
OlegTar, 2016-11-07 20:48:01

When to use try and catch?

At the interview, I was asked what is the general rule for when to do try and catch.
I answered when there is work with external resources, where the occurrence of an error does not depend on the programmer. For example, when there is work with files or a database (the file may not exist, the disk may run out of space, the connection to the database may fail)
The answer turned out to be incomplete.
Allegedly there is some kind of rule when you need to use try catch
. I myself tend to believe that the correct answer is: you need to use try catch when you can’t get by with if / else checks.
What do you think? What is the correct answer?
UPD:
A friend of mine said that you should use try / catch when a runtime exception might occur. I like it as long as I think it's the correct answer.
Answer:
Summing up, I think that this answer is correct:
you need to use try / catch when a run-time exception may occur or when, after an error, further work of the program or function does not make sense.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
ayazer, 2016-11-08
@OlegTar

it is strange that no one said that try-catch should still be used when we do not know how to handle the situation that has arisen, and we just need to return control higher up the stack.

X
xozzslip, 2016-11-07
@xozzslip

At interviews, they often ask all sorts of game. Make it a rule to find out the correct answers after the interview. To then laugh with the boys :)

P
polifill, 2016-11-07
@polifill

Yes, whichever is more convenient.
try or if
As you personally feel more comfortable.
Look, in the newfangled Go language, try was generally abandoned.
True, defer was introduced there.
Exceptions have already shown their failure neverworkintheory.org/2016/04/26/java-exception-ha...
And they were abandoned in Google in C ++ code
https://google.github.io/styleguide/cppguide. html#...

M
MrTimon, 2017-01-25
@MrTimon

as an option, you can use load - api.jquery.com/load . But as for me, it’s better to send an Ajax request and on the server do everything you need to return the block and insert it in the right place.

$('#button1').click(function() {
   $( "#result" ).load( "bloks/blok3.php" );
});
$('#button2').click(function() {
   $( "#result" ).load( "bloks/blok1.php" );
});
$('#button3').click(function() {
   $( "#result" ).load( "bloks/blok2.php" );
});

D
Dark Hole, 2017-01-25
@abyrkov

This phenomenon is called hijax and it consists of ajax requests. In short, we request a page with Ajax and insert it. There is also a more universal option - use the load function - ruseller.com/jquery.php?id=16

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question