Page 170 - CTS - CSA TP - Volume 2
P. 170
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 106 : Handle common exceptions
Objectives
At the end of this exercise you shall be able to
• develop Java programs using various exceptions.
Requirements
Tools/Materials
• PC / laptop with windows OS
• SDK software
• Test editor (Visual studio/ subline/ notepad)
Procedure
1 NullPointerException:
• Description: Occurs when attempting to access members (methods or fields) of an object that is null.
• Handling Approach: Check if the object is null before accessing its members.
public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
// Step 1: Declare a String variable and initialize it to null
String str = null;
// Step 2: Attempt to access the length() method on a null reference
int length = str.length(); // This will throw a NullPointerException
// Step 3: Display the length of the string (this won’t be reached due to the exception)
System.out.println(“Length of the string: “ + length);
} catch (NullPointerException e) {
// Step 4: Catch the NullPointerException and handle it
System.out.println(“Caught NullPointerException: “ + e.getMessage());
}
}
}
Output:
155
CITS : IT & ITES - Computer Software Application - Exercise 105