Exception handling mechanism helps java applications solves the problem of unexpected termination of the program.
Handling exception is of utmost important for any programmar to protect their code from unwanted termination thus exhibiting anamolous behaviour.
In java, we have various keywords that helps us in handling exception.
We have listed them below and will be learning in detail about each of them in next few chapters.
Different ways of handling java exception
Try-catch block→ Use try catch block to enclose the code that might throw any exception. A try block can be supported with multiple catch block each of them handling different kind of exceptions.
Try-catch-finally block→ Use try catch block to enclose the code that might throw exception followed by finally block to close the resources that you might have opened. finally block will surely get executed irrespective of whether exception is caught or not. So the finally block in java mostly contains any clean-up code like closing open connection, stream etc.
Throw→ throw keyword is used to explicitly throw an exception in java. You can only throw one instance of any exception class at a time using throw keyword. It is also used to throw custom exception in java.
Throws→ throws keyword is used to declare exceptions that your code might throw in case you are not handling it yourself. The declaration is done at the method level and it helps the caller of the method be aware of the kind of exception the called method may throw so that they can handle them accordingly.
Custom Exception→ Inspite of the fact that java provides lots of in-built classes to handle exception in best possible ways but there are certain limitations with the in-built features. In practical world, we may want to throw our own customized exceptions. So java creators understood this fact very well and provided the java programmars with the facility to create their own exception and use them as per their requirement.
We will learn in depth about each of them in upcoming chapters.
Before we learn how to use these to handle exception in our code lets first know about hierarchy of java exception classes.