![]() |
VOOZH | about |
An unexpected unwanted event that disturbs the program's normal execution after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the expected termination of the program.
π Top-5-Exceptions-in-Java-with-ExamplesIllustration: Considering a real-life example
Suppose books requirement is from Delhi library at runtime if Delhi library is not available to provide books due to some transport issues. Then Delhi library suggests taking books from Indore library to continue the rest of our work. This way of defining alternatives is nothing but exception handling.
Exceptions are divided into two types. These are as follows:
1. Checked exceptions: These are the exceptions that can be detected by the compiler at the time of execution of the program, and warning messages are displayed.
2. Unchecked Exceptions: These are the exceptions that are missed out from the compiler check giving birth to abrupt flow.No warning messages are displayed as these exceptions are not detected by the compiler.
Now the above two types of exceptions are categorized as follows:
The top 5 exceptions that occur most are as follows:
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Example:
Output:
π IllegalArgumentException(IAE)The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.
Example:
Output:
π ArrayIndexOutOfBoundsExceptionStackOverflowError is an error that Java doesnβt allow to catch, for instance, a stack running out of space, as itβs one of the most common runtime errors one can encounter. The main cause of the StackOverflowError is that we havenβt provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.
Example:
Output:
π StackOverFlowErrorThis exception is thrown when forcefully string is been converted to numeric value but the format of the input string is not supported. For example, parsing a string to an integer where NULL is assigned in the string throwing unchecked exceptions.
Example:
Output:
π NumberFormatExceptionNull is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. It is a runtime Exception where a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.
Example:
Output:
π NullPointerExceptionNote: There are two more exceptions that do occurs frequently
- NoClassDefFound where the definition for the corresponding class is missing
- ClassCastException is runtime exception where a class is improperly casted from one type to another.