Java Exception : Exception in Java can be defined as abnormal activity due to unwanted execution of code which should be avoided. But as we know writing too many complex logics can lead to execution of unwanted code and it can disrupt our normal flow.
To avoid such scenarios we have an option option called EXCEPTION HANDLING, by using EXCEPTION HANDLING we can make our execution normal in case of any disruption.
There are 2 ways to handle the exception. If we want the doubtful code which can throw exception and interrupt our execution flow , in this case we can use try and catch block and can do the required things and log the message that this hasn't work and can print the exact failure message with the help of stack trace.
Let's understand with an example : below code is without Exception handling which will through Arithmetic exception.
package C4CAMPUS;
public class ExceptionExample {
public static void main(String args[]){
int a =10;
int b= 0 ;
int c= a/b;
System.out.println("Exception will be thrown before this line");
}
}
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at C4CAMPUS.ExceptionExample.main(ExceptionExample.java:9)
We can see exception has been thrown without printing the last line as flow got interrupted . Now we will handle it via try catch block as below.
package C4CAMPUS;
public class ExceptionExample {
public static void main(String args[]){
int a =10;
int b= 0 ;
try{
int c= a/b;
}catch (Exception e){
System.out.println(e);
}
System.out.println("Exception will be thrown before this line");
}
}
Output :
java.lang.ArithmeticException: / by zero
Exception will be thrown before this line
As we can see it has printed the exception message but didn't interrupt our execution flow and it went to next line of execution and that's the reason we got printed Exception will be thrown before this line.
I hope use of exception can be clear till this post. Now let's discuss the other ways of handling the exception.
We have 2 keywords throw and throws. In most interview it is common question to explain the difference between throw and throws keyword.
As in above code we handle the exception using try catch block but think like your logic is correct as per your understanding and whoever is calling the method they are providing wrong input to your method. Instead of handling calling method's mistake we have decided that we will throw back them the exception in case of their mistake. We won't take care of calling method's mistake. Let calling method only handle the exception . This is common human nature as we are not that great.
So to do this we have these 2 keywords throw and throws. Now if we know the lines so we will put lines inside try block and in catch block using throw keyword we will throw back the exception to the calling method and also we can put our custom message to calling method along with exception stack trace. Below is an example of using throw keyword.
package C4CAMPUS;
public class ExceptionExample {
public static void main(String[] args) {
ExceptionExample exceptionExample = new ExceptionExample();
String message =exceptionExample.method1();
System.out.println(message);
System.out.println("Exception will be thrown before this line");
}
public String method1() {
try {
String message = method2(0);
System.out.println(message);
} catch (Exception e) {
System.out.println(e);
}
return "I am method 1";
}
private String method2(int num) {
try {
int a = 10 / 0;
} catch (Exception e) {
throw e;
}
return "I am method 2";
}
}
Output :
java.lang.ArithmeticException: / by zero
I am method 1
Exception will be thrown before this line
In above example we can see that actual code i.e 10/0 is in method2 and Arithmetic exception has been thrown from this line but instead of handling it we have thrown back to calling method1 to handle it and print the Exception message and for this we have used the keyword throw. This way we can propagates exception till root calling method that is main method. If no one has handle the exception then it will go to main method and disrupts our execution flow.
Now use of throws keyword is similar to throw but only difference is that instead of writing the logic to throw an exception using try catch block we can have the expected Exception names in method signature only so while calling this method , caller will get alert to be ready to handle these kinds of Exceptions. Below is an example of using throws keyword.
package C4CAMPUS;
public class ExceptionExample {
public static void main(String[] args) {
ExceptionExample exceptionExample = new ExceptionExample();
String message =exceptionExample.method1();
System.out.println(message);
System.out.println("Exception will be thrown before this line");
}
public String method1() {
try {
String message = method2(0);
System.out.println(message);
} catch (Exception e) {
System.out.println(e);
}
return "I am method 1";
}
private String method2(int num) throws Exception,ArithmeticException
{
int a = 10 / 0;
return "I am method 2";
}
}
Output :
java.lang.ArithmeticException: / by zero
I am method 1
Exception will be thrown before this line
As we can see output is same only difference in both the code is that in case of throw we have used try catch block inside our code while in case of throws keyword we have define the expected Exception at method signature level private String method2(int num) throws Exception,ArithmeticException.
There are 2 types of Exception
1) Checked Exception (Compile time)
2) Unchecked Exception (Runtime )
To understand Compile time exception in simpler way just think like a train ticket checker and in case of Exception JVM will be our ticket checker and it can inform us before compile of our class that these are suspected code who can throw exception so better fix it before going for compilation. In general way at the time of train boarding we will have list of defaulters.
While in case of Runtime our ticket checker will have no idea because these are expert in skipping JVM checklist and can onboard to train in running state means while running the program they came into picture and if not handled then can disrupt the execution flow.
Common examples of Compile and Runtime Exception can be as below
Throwable - > Exception ->Compile Time :
- IOException
- CharConversionException
- EOFException
- FileNotFoundException
- InterruptedIOException
- ArithmeticException
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
- ClassCastException
- IllegalCallerException
- IllegalMonitorStateException
- IllegalStateException
Apart from Exception we can have Error also and Error can not be handled. Throwable has 2 subtype Exception and Error. Exception we already discuss and below are some example of Error, you can face this error in case you are doing something out of box things.
Throwable - > Error ->- InstantiationError
- NoSuchFieldError
- NoSuchMethodError
- NoClassDefFoundError
- UnsatisfiedLinkError
- InternalError
- OutOfMemoryError
- StackOverflowError
- UnknownError
Please let us know in comment section if you have any doubt and i will request you to go to previous Basic Java tutorials post.
BASIC JAVA :
Comments
Post a Comment