In this article, we will discuss exception handling in Java in detail with examples
1. Exception:
- An event which disrupts normal execution of a program is known as exception
2. Exception handling:
- When such event occurs during execution of the program, in Java terms it is called as exception thrown or exception raised at runtime
- Which results in abrupt or abnormal termination of the program and rest of the program (code i.e.; after the line where exception is raised) won’t be executed
- To avoid abnormal termination of the program, all possible exceptions that could be thrown/raised needs to be handled
- This is known as exception handling in Java
- This helps to maintain graceful termination of the program
3. Alternative definition for Exception Handling:
- Defining alternative solution or ways to maintain normalcy of the program for its graceful termination
- Handling an unexpected event which results due to programmatic error or non-availability of required resources during run-time
- Note: exception handling doesn’t mean that programmer correcting those raised exception, rather providing alternative way to continue with the rest of the program/code for its normal termination (graceful termination)
Q) How to handle exception in Java ?
- The next obvious question is that, how to handle the exception raised or exception thrown
- One way to handle exception in Java is, provide try-catch blocks
- We will discuss and study try-catch blocks in detail in subsequent articles
- For time being, understand try-catch blocks or clause can be used to handle exception thrown/raised during program execution at runtime
Pseudo code for exception handling:
try {
// program code that
// could raise or throw exception
}
catch(ExceptionType var) {
// handle exception here
// provide alternative solution or way
}
4. Examples on Exception handling:
4.1 When Arithmetic exception is raised
- In this example, arithmetic exception is thrown during execution/runtime as we are performing division by zero
- So, any exception raised in the try-block will be caught in the catch-block and respective actions can be taken from this block like providing handling code
try {
// divide by Zero
int result = 19/0;
}
catch(ArithmeticException aex) {
// exception handling code
System.out.println("Exception handling code");
}
4.2 When null pointer exception is raised
- In this example, null pointer exception is thrown during runtime as we are counting/checking length on a null string
- So, any exception raised in the try-block will be caught in the catch-block and respective actions can be taken like alerting the users to enter valid string
- Note: null string & empty string are different, as invoking length() method on empty string returns length as ZERO (0) whereas on null string it raises exception as explained above
try {
// checking length on NULL String
String str = null;
int lenghtOfString = str.length();
}
catch(NullPointerException npex) {
// exception handling code
System.out.println("Alert !! enter valid String");
}
4.3 When Array Index out of Bounds exception is raised
- In this example, Array Index Out of Bounds exception is thrown during execution/runtime as we are trying to assign a character at 7th position whereas its declared size is 4
- So, any exception raised in the try-block will be caught in the catch-block and respective actions can be taken like alerting users by printing simple message like Invalid assignment
try {
// trying to assign a character at 7th place for a char[] of 4
char[] ch = new char[4];
ch[7] = 'B';
}
catch(ArrayIndexOutOfBoundsException aioobex) {
// exception handling code
System.out.println("Invalid assignment");
}
In next article, we will see what internally happens when exception is raised during runtime without any handling code for abnormal termination
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!