Exception Handling()
-
it is an event that stops the normal flow of execution of the program and terminates the program abnormally.
-
Exception always occurs at runtime.
-
There Is two type of Exception:
-
Checked Exception.:-The exception which is checked by the compiler at the compilation time. Ex: IOException,ClassNotFoundException.
-
Unchecked Exception: The Exception which Cant be checked by the compiler at the compilation time and directly occurs at runtime is called an unchecked Exception.
Ex:NullPointerException,StringIndexOutOfBoundsException.
Error: Error is the type of unchecked Exception which occurs due to programmers mistake, end-user input mistake, resource unavailability or network problem etc.
OutOfMemoryError
StackOverFlowError
etc.
5 keywords to handle Exception:
try
catch
finally
throw
throws
possible combination:
-
try-catch
-
try-catch-catch
-
try-catch-finally
-
try finally
-
try-catch-catch-finally
try:
the statement which may throw errors.
Catch
this block handles the error and we can write alternate code to run.
Finally:
this block contains code which must run at any cost even if the error is generated or not.
________________________________________________________________________________
Whenever exception occurs in try block the corresponding matching catch block will be executed.
If the exception doesn't occur in the try block, catch block will not be executed but finally will execute.
There are three cases only finally will not execute
1.When the exception occurs before the try block.
2. When JVM stopped explicitly by the System.exit(0);
3. When the exception is not handled by any of the corresponding catch blocks ..finally will not be executed.
In child class exception is occurring or there is a possibility of occurrence is there we can catch the parent class exception the catch block.
Throws:
it is used to handle the exception by delegating the responsibility of the exception handling to the caller method.
It is more useful in checked Exception.
We can throw parent class exception also in place of child class exception.
It is used to transfer(Delegate ) the responsibility to the caller method.
We can handle multiple exceptions simultaneously by using by using throws.
Throw :
In child class exception is occurring or there is a possibility of occurrence is there we can catch the parent throw keyword is used to hand over user-defined exception to the JVM.
There are two approaches to create user-defined Exception.
1. By default Constructor
2.By Argumented Constructor.
User Defined Constructor are of Two type:
1.Checked: It is created by using the exception class.
2.Unchecked: Unchecked User-defined Exception are created by using runtime exception class.
Comments
Post a Comment
share your thoughts ....