- Exceptions in real life are rare.
- Exceptions are usually used to denote something unusual that does not conform to the standard rules.
- In programming, exceptions are events that arise due to the occurrence of unexpected behavior in certain statements, disrupting the normal execution of a program.
- Trying to access the 11th element of an array when the array contains of only 10 element (ArrayIndexOutOfBoundsException)
- Division by zero (ArithmeticException
- Accessing a file which is not present (FileNotFoundException)
- Failure of I/O operations (IOException)
- Illegal usage of null. (NullPointerException).
The default handler prints the name of the exception along with an explanatory message followed by stack trace at the time the exception was thrown and the program is terminated.
|Types of exceptions in java|
- try..catch : try/catch block can be placed within any method that you feel can throw exceptions.
All the statements to be tried for exceptions are put in a try block catch block is used to catch any exception raised from the try block. If exception occurs in any statement in the try block control immediately passes to the corresponding catch block.
- throw : used to explicitly throw an exception. useful when we want to throw a user-defined exception. The syntax for throw keyword is as follows: throw new ThrowableInstance;
For example : throw new NullPointerException();
- throws : is added to the method signature to let the caller know about what exception the called method can throw. responsibility of the caller to either handle the exception (using try…catch mechanism) or it can also pass the exception (by specifying throws clause in its method declaration). If all the methods in a program pass the exception to their callers (including main( )), then ultimately the exception passes to the default exception handler.
- finally : finally block is executed in all circumstances if the exception occurs or
it is normal return (using return keyword) from methods. mandatory to execute statements like related to release of resources, etc. can be put in a finally block. The syntax of the finally keyword is as follows:
Rohan Chaubey is the founder of “Be Rohanlicious” – a blog that teaches you to be smart with social media, blogging and programming.
Rohan is on a mission to help all the enthusiastic souls like you, who want to “make it to the next level” and stand out of the crowd.
His e-book “Make People Want You” is releasing soon. Allow him to inject awesomeness in your life by signing up to his list here.