What is Exception Handling in Java?
Exception handling in Java is a mechanism that allows developers to manage runtime errors gracefully without crashing the program. Java provides a structured way to handle exceptions using the try, catch, finally, and throw keywords.
- try block: Wraps the code that might throw an exception.
- catch block: Handles the exception if it occurs.
- finally block: Executes code regardless of whether an exception occurs or not.
- throw keyword: Used to explicitly throw an exception.
- throws keyword: Declares exceptions a method might throw.
Common String Exceptions in Java
When working with Java strings, several exceptions may arise. Understanding these is key to writing robust code.
- NullPointerException
Occurs when you attempt to perform an operation on anullstring reference.
public class NullStringExample {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Caught Exception: String is null!");
}
}
}
Explanation:
strisnull, so callingstr.length()triggers aNullPointerException.- The
catchblock handles it, preventing the program from crashing.
- StringIndexOutOfBoundsException
Occurs when trying to access a character index that is outside the bounds of the string.
public class StringIndexExample {
public static void main(String[] args) {
String str = "Java";
try {
char ch = str.charAt(10);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught Exception: Index out of bounds!");
}
}
}
Explanation:
str.charAt(10)is invalid becausestrhas only 4 characters.- The exception is caught, and a descriptive message is displayed.
- NumberFormatException
Occurs when converting a string to a number, but the string is not properly formatted.
public class NumberFormatExample {
public static void main(String[] args) {
String str = "123ABC";
try {
int number = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Caught Exception: Invalid number format!");
}
}
}
Explanation:
Integer.parseInt(str)expects only numeric characters.- The presence of
ABCtriggers aNumberFormatException, which is handled gracefully.
Best Practices for Exception Handling with Strings
- Validate Input Before Processing
Always check if a string isnullor empty before performing operations.
if (str != null && !str.isEmpty()) {
System.out.println(str.length());
}
- Use Specific Exceptions
Catching specific exceptions likeNullPointerExceptionorStringIndexOutOfBoundsExceptionis better than catchingExceptiondirectly. This makes debugging easier. - Avoid Silent Failures
Always log exceptions or provide meaningful feedback to the user rather than ignoring them. - Combine try-catch with Finally
Usefinallyto close resources or perform cleanup tasks, ensuring your application remains stable.
Step-by-Step Example: Safe String Manipulation
Here’s a practical example combining multiple exception handling concepts:
public class SafeStringManipulation {
public static void main(String[] args) {
String[] strings = {"Hello", null, "1234", "Java"};
for (String str : strings) {
try {
System.out.println("String length: " + str.length());
int number = Integer.parseInt(str);
System.out.println("Converted number: " + number);
} catch (NullPointerException e) {
System.out.println("Error: String is null!");
} catch (NumberFormatException e) {
System.out.println("Error: Cannot convert string to number: " + str);
} finally {
System.out.println("Processed string: " + str);
System.out.println("-----------------------------");
}
}
}
}
Explanation:
- Iterates through an array of strings, handling multiple exceptions.
NullPointerExceptionoccurs fornullstrings.NumberFormatExceptionoccurs for non-numeric strings.finallyexecutes after each iteration, ensuring consistent logging.