Escolar Documentos
Profissional Documentos
Cultura Documentos
Error vs Exception:
Eg: RAM is going out of memory. We cannot do anything about that. It’s an example for Error.
Exception Hierarchy in Java:
All Exceptions and Errors are subclasses of class “Throwable” which is the base class of hierarchy.
It is divided into 2 branches.
One is Exception and the other is Error.
Exception : This called is used for Exceptional conditions which a user program can catch.
Eg: Null Pointer Exception , Runtime Exception etc.
Error: This is used by the Java Run time system to indicate that the errors that has to do with the java
run time environment itself . i.e JRE.
Eg: Virtual Machine error or Stack over flow error etc.
So how JVM handles exception???
When ever inside a method if an exception has occurred , Then the method creates an object known as
Exception object and hands it to the Run time system.
This Exception object contains name and description of the exception and all the current state of the
program the exception has occurred.
Creating an Exception object and handling it to the Run time system is known as Throwing an
Exception.
Using try , catch and finally blocks these exceptions can be handled.
This is how JVM handles exception internally.
Checked vs Unchecked Exceptions:
Eg: checked exception like IOException , Unchecked exception like null pointer exception , Array
Index Outbounds exception , Divided by Zero Exception etc.
Basic Example:
Types of Exceptions:
Built-in Exception:
These are the exceptions that are available in java built in library and they are suitable to explain
certain error situations.
Eg :
Nested try:
Multi Catch:
If you want to perform various tasks on the occurrence of various exceptions then you should go for
multiple catch block.
Finally block: This is to close the DB connections or close the opened files etc. No matter whether
the exception is handled or not finally block will always be exceuted.
On using finally block the catch block is optional. If we don’t provide catch and only provide finally
then after try finally will be executed and the rest of the statements wont get executed if exception
occurs.
Throws:
Incase if we are lazy enough to handle the error but JVM is warning you to take care of the error ,
what will do is , rather than handling the error will just suppressed the error using throws keyword.
Exception might or might not occur , not sure.
It will just suppress the error.
Throw keyword:
What if wanted to throw an exception based on a condition , like based on a if condition I want to
print an error. To forcefully throw an error we will use Throw keyword.