What is the purpose of using try, catch blocks?

Is this a replacement for if then blocks? I've seen a lot of code where they are used like this.

-2


a source to share


3 answers


No, this is not a replacement for an if and then a block, it serves a completely different purpose. The purpose of try, catch block is to try to do something that might not work and throw an exception (for example, read a file from disk, but the file might be missing, etc.). Once you find the exception, you can deal with it.



try {
   riskyOperation();
catch (ExpectedException) {
   handleException();
}

      

+11


a source


The purpose of the try catch blocks is so that you can try and do the action, and then if an exception is thrown, catch the exception and handle it gracefully rather than fail.



+1


a source


A try block is a block of code in which exceptions occur.

The catch block captures and handles block exception attempts.

0


a source







All Articles