W12 - Lesson 11. Basic Exception Handling - PRESENTATION
W12 - Lesson 11. Basic Exception Handling - PRESENTATION
What is Exception?
- is a problem that arises during the execution of a program.
- it occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the
JVM has run out of memory.
Handling Exception
try {
// Protected code
}catch(ExceptionName e1) {
// Catch block
}
For example:
public class ExceptionSample {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
The result of the example above is:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple Catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks looks like the following:
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}
Here is code segment showing how to use multiple try/catch statements:
Below is the output of the example above:
In the above example, we have two lines that might throw an exception:
arr[5] = 5;
The statement above can cause array index out of bound exception and
result = num1 / num2;
this can cause arithmetic exception.
Notes:
• At a time, only single catch block can be executed. After the execution of
catch block control goes to the statement next to the try block.
Notes:
• A catch clause cannot exist without a try statement.
• It is not compulsory to have finally clauses whenever a try/catch block is present.
• The try block cannot be present without either catch clause or finally clause.
• Any code cannot be present in between the try, catch, finally blocks.