Exception Handling


Introduction: Exception is any undesired condition or a case which can interupt nor mal flow of any application.
During the development of any application regardless of implementing language, there might be some cases in which some special cases can results in unexpected behaviour. You may want to handle these cases according to different situations. For example, In some cases you may want to stop execution your application, and in other cases you may want to redirect flow of application or return with some message so that end user knows the problem and can take appropriate action.

Reasons: In an application, there might be multiple reasons for occuring exceptions.
i.g. wrong data format, wrong or invalid data provided by client, hardware failure, network connection failure, Database server down etc.

So, you like or not, exceptions can occured in any application, you need to deal with it. Fortunatly, mostly languages come with exception handling capablities. Java can handle exceptions in a very effective and robust way. When any exception occured during execution of your code, JVM stops execution and tries to find appropriate handler registered with application to handle occured application. If JVM could not find any exception handler, it just kill the program and your application may crash. But if any handler is available to handle occured exception, JVM create an instance of that exception and make it available to exception handler. This exception object contains very useful information and helps to take proper action.

Exception object has following exception
Method hierarchy
Line number where the exception occurred
Type of exception
Reason of exception and so on...

Catching Exception: Action defined in exception handler to hanlde particuler action is called catchin the exception. If any exception occured, and it is catched, running application will not be terminated unexpectedly by JVM.

Throwing Exception: Instead of catching any exception you as developer have option to delegate responsibility of catching exception to next level. This mechanism is called throwing exception.

Rethrowing Exception: During execution of an application, if any exception occurred and we catch that exception in our code using catch block but instead taking proper action we create new instance of some other type of exception (Usually Custome Exceptions) and throw it manually using throw keyword. Thats called rethrowing exception.

How to handle or throw exception, we are going to learn it soon.


As stated earlier, when any exception is raised an exception object is getting created. Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.
Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError.
Checked Exceptions: There are some exceptions that are actualy check by compiler at the time of compiling the code. If your code can throw some exceptions that are directly extends Exception class or not extending RuntimeException class or its subclasses, compiler will check these exception at compile time and will force you to catch or re-throw occured exception. Checked Exceptions can be anticipated in a program and can be recovered, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose.
Unchecked Exceptions or Runtime Exception: Unchecked Exceptions are the exceptions that actually orrured at runtime and can not be anticipited at compile time. If any exception class is extending RuntimeException or it subclass it will be Unchecked Exception. Compiler will not force you to catch or throw it. Its complitly up to developer to handle it or to leave for runtime.
Mostly time Runtime Exceptions are cause by bad programming, for example trying to retrieve an element from the Array, or the NullPointerException etc.
Exception Handling in Java – Useful Methods
Throwable is a class at the top of hierarchy of exceptions. It comes up with some set of methods explained below. It has many sub-classes, we have already discussed some of them.
Some of the useful methods of Throwable class are;
public String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
public String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
public synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
public String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
public void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.
 Next

Sorting Objects | Comparator



Comparator interface is used to provide user defined sorting of java objects. It helps you create multiple ordering sequences. With comparable interface you can define only single sorting criteria but with Comparator interface you can define multiple sorting criteria. You just need to create separate classes implementing Comparator interface, like below example classes.
Sort student objects by student name:

public class NameComarator implements Comparator<Student> {
       @Override
       public int compare(Student o1, Student o2) {
             return o1.getName().compareTo(o2.getName());
       }
}

Sort student objects by student roll number:
public class RollNumberComparator implements Comparator<Student> {
       @Override
       public int compare(Student o1, Student o2) {
             if (o1.getRollNum() < o2.getRollNum()) {
                    return -1;
             } else if (o1.getRollNum() == o2.getRollNum()) {
                    return 0;
             } else
                    return 1;
       }
}

public class Student {

       private String name;
       private String level;
       private int rollNum;

       public String getName() {
             return name;
       }

       public void setName(String name) {
             this.name = name;
       }

       public String getLevel() {
             return level;
       }

       public void setLevel(String level) {
             this.level = level;
       }

       public int getRollNum() {
             return rollNum;
       }

       public void setRollNum(int rollNum) {
             this.rollNum = rollNum;
       }

}

Comparator interface has two methods, compare() and equals(). Each class has default implementation of equals() method available from Object class, so if you think overriding equals() method is not required, you can skip it. But you must have to provide implementation of compare() method. Compare method accept two objects and returns -1, 0 or 1 according to sorting/ordering logic defined.

Pros & Cons:   
  • Comparator interface allows you to compare two objects.
  • For using comparator, you need to create new class for each implementation and comparing criteria.
  • It provides very loose coupling, If in future you want to any other criteria for comparing your objects you don’t have to modify your existing class.
  • You can provide multiple comparison logic for your class.
  • You don’t require actual code of a class you want to compare. It helps you writing comparison logic for third party library classes too.

Sorting Objects | Comparable


While developing any java application, many time we need to sort our objects. Java provides two different mechanism to sort your objects.
  1. Comparable
  2. Comparator 
Comparable is an interface comes with compare() method. This is used to compare one instance of a class with other object of same class. The class needs implement Comparable interface to become comparable.  Compare method return -1, 0 or 1. 
Let’s have Student class example. Create two object s1 and s2.
s1.compare(s2) => -1 if s1 is smaller then s2
                         =>  0 if s1 equals to s2
                         =>  1 if s1 is greater then s2
Check code example of Student class implementing comparable interface. You can try with different comparison logic by updating compare logic inside compare() method.




public class Student implements Comparable<Student> {

       private String name;
       private String level;
       private int rollNum;

       @Override
       public int compareTo(Student s) {
             // Write your logic to check ordering of you object
             // You must return -1, 0, 1 on the basis of object1 is less, equal or
             // greater than this object
             if (s.getRollNum() < this.rollNum) {
                    return -1;
             } else if (s.getRollNum() == this.rollNum) {
                    return 0;
             } else
                    return 1;
       }

       public String getName() {
             return name;
       }

       public void setName(String name) {
             this.name = name;
       }

       public String getLevel() {
             return level;
       }

       public void setLevel(String level) {
             this.level = level;
       }

       public int getRollNum() {
             return rollNum;
       }

       public void setRollNum(int rollNum) {
             this.rollNum = rollNum;
       }

}



Pros & Cons:   
  • Comparable interface allows you to compare two objects.
  • For using comparable you do not need to create any separate class, you can just provide your sorting logic inside compare method of your existing class.
  • It provides very tight coupling, If in future you want to write any other criteria for comparing your objects you have to modify your class.
  • You can provide only a single comparison logic in your comparable class.
  • You must have access to the code, if you don't have code of class, and you want to write your comparison logic for that class, you can't do that.

As you see there are some issues with Comparable interface, we can overcome these problems using Comparator interface.

Please Click Here for learning Comparator.

Powered by Blogger