As we discussed, Exceptions are errors that abrupt the normal flow of a program. It often occurs when constraints or rules of that language get violated.
These exceptions can be handled by creating an exception handler. Try, catch, finally and resources are the components that help to create an efficient and effective exception handler, they rescue a program from being crashed.
Try Statement
- This is the very first step to construct an exception handler. It encloses all critical statements which might trigger an exception.
- Try block monitors each & every critical statement. If a constraint gets violated, then it would throw an exception object.
- A Try can have multiple catch statements.
- It always associates with either a catch statement or a finally statement, forming a pair such as try-catch or try-finally.
try{ // code here }
Catch Statement
- A catch statement is an exception handler that handles the exception object thrown by try statement.
- Thrown exception object is caught by an appropriate catch block.
- It accepts an argument which represents an exception object of the specific type.
- A single catch statement can handle multiple exceptions
- No code can be put in between try and catch statement. Meaning, once a try block ends up, immediately after that, a catch or finally block should be there in a program.
- If a try block has multiple catch statements, then the compiler would choose that catch block which keeps the appropriate type of that exception object. catch (ExceptionType objName){ // code }