Skip to main content

Java Exception : Exception Handling in Java

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 :

  1. I­O­Exception
  2. Char­Conversion­Exception
  3. E­O­F­Exception
  4. File­Not­Found­Exception
  5. Interrupted­I­O­Exception
Runtime­Exception :
  1. Arithmetic­Exception
  2. Index­Out­Of­Bounds­Exception
  3. Array­Index­Out­Of­Bounds­Exception
  4. String­Index­Out­Of­Bounds­Exception
  5. Class­Cast­Exception
  6. Illegal­Caller­Exception
  7. Illegal­Monitor­State­Exception
  8. Illegal­State­Exception

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 ->
  1. Instantiation­Error
  2. No­Such­Field­Error
  3. No­Such­Method­Error
  4. No­Class­Def­Found­Error
  5. Unsatisfied­Link­Error
  6. Internal­Error
  7. Out­Of­Memory­Error
  8. Stack­Overflow­Error
  9. Unknown­Error

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 :

  1. BASIC OVERVIEW OF JAVA
  2. PRIMITIVE TYPES AND WRAPPER CLASS
  3. JAVA OPERATORS
  4. LOOPS IN JAVA
  5. NAMING CONVENTION WITH FACTORIAL PROGRAM
  6. EXCEPTION IN JAVA

Comments

Popular posts from this blog

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ;

OOPS Concept in Java : ENCAPSULATION

OOPS Concept in Java : ENCAPSULATION   This OOPS concept can be used to make things simpler in case of software development . Main purpose of this concept is to hide the properties of any class and give access to fetch and modified based on business criteria.  A simple example can be a POJO ( Plain Old Java Object) in which all the properties of a class can be private and through getter and setter method of properties we can fetch and update the properties of Object. So instead of having direct access to properties we have created 2 methods to make the CLASS things encapsulated in single unit while access to it is via 2 public methods.   Just consider we have requirement that once the object is created its value should not be changed then simplest way to achieve this  can be done by just removing setter method and we will keep only getter methods to access Object properties . In this case after Object creation whatever the value of Object properties has been initialised it will b

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If Object is of PARENT