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

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

Overview of time and space complexity for sorting algorithm

Bubble sort : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). Selection sort : In selection sort we will divide the Array in 2 parts , sorted and unsorted and select the min element from unsorted and will copy to sorted array.      Time Complexity for selection sort also is O(n^2).      space complexity for bubble sort will be O(1). Insertion sort :  In insertion sort, Same process like selection sort , we will divide the array in sorted and unsorted array and we will select element from unsorted array and will insert it into sorted array at its proper...