Smeggles
Smeggles

Reputation: 67

What is the purpose of using try, catch blocks?

Is it a replacement for if, then blocks? I have seen a lot of code where they are used like that.

Upvotes: 0

Views: 11848

Answers (3)

Sachith Wickramaarachchi
Sachith Wickramaarachchi

Reputation: 5872

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

A catch block catches and handles try block exceptions.

Upvotes: 0

ninesided
ninesided

Reputation: 23273

The purpose of try catch blocks to allow you to try to perform and action and then if an exception occurs, catch the exception and deal with it gracefully rather than crashing.

Upvotes: 3

Ankit
Ankit

Reputation: 1931

No, it is not a replacement for an if, then block, it serves an entirely different purpose. The objective of a try, catch block is to try and do something which could fail and raise an exception (e.g., read a file from disk, but the file might not be there, etc.). After catching an exception, you can handle it.

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

Upvotes: 15

Related Questions