Exception and Error Concept Simplified in Java

An Exception is an unusual or abnormal condition that occurs during the execution of the program. If Exceptions are not handled properly or taken care,the program will terminate abruptly  or provide wrong results. In other word,Exceptions are events that interrupts the normal flow of the execution.(Disruption during normal flow of execution).
class throwable is used to represent all Exceptional conditions.Exceptions are used for exceptional condition that user program can catch.We need to remember that Error  is different from Exception.Errors are used to catch at normal condition.In some cases errors are not supposed to catch and handle.They may be beyond the control of Programmers. If JVM is not able to allocate memory to create new objects ,during the program execution,the JVM will throw an error. Program will get terminated.In this situation,programmer can not handle

Java's Exception handling brings runtime error management into object oriented world.
How do we get Exception in java? Exception in thread "main" with some details popularly known as stack trace. Now if user gets such kind of Exception,it is very tough for an user to understand the issue. Instead if we get a clear message , may be, the non technical person will never come to IT team.Popular Exceptions are --

  • A network connection is lost in the middle of communication
  • Product not available
  • Can not divide by zero
  • if user inserts invalid data(Invalid username and password)
  • A file that needs to opened can not be found
  • JVM ran out of memory.
Exceptions are encapsulated into object that extends Throwable class.Like any other object we can create Exceptions on the heap using new keyword and a constructor gets called. Read here for Class Exception more.If a method throws an Exception , it must assume that it is caught and dealt with.The good part of java Exception is that it allows us to deal with the problem in one place and allows us to deal with the error in some other place.
Lets check the popular Exception generation code:
Lets observe the below code:
public class myException{
public static void divide(int x,int y)
int z=x/y;
public static void main(String args[]){
//Exception occurs here
The output of the program will be as below:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at myException.divide(myException.java:4)
at myException.main(myException.java:8)
It is called method stack trace.
The first line says about the type of Exception-java.lang.ArithmeticException
The first line also says the Exception message-/ by zero
And the below two lines talks about the location/package/class/method/filename where the Exception really occurred. If we observe it more details, the second line talks about where the Exception is actually occurred and how it is propagated to the calling function.
During execution when an Exception occurs an object of the respective Exception class is created and thrown in the method which causes the Exception.Now the method may choose two things:

  1. To catch the Exception and can guard the Exception against premature exit by a block of code.
  2. Pass the Exception object to the calling method.
Propagation of Exception in realtime:

               ------->                ------->                                         ------->
Runtime    Call                    Call                                               Call
            --------------Main()----------------Calling Function(1)------------Calling Function(n)
System    Exception            Exception                                    Exception
              <----------             <----------                                      <----------

We do not have a handler for any kind of Exception here.Whenever an Exception occurred , the run time environment (JRE) generates the Exception object and throws it. The moment an Exception object is thrown, further Exception steps and if it is not taken care of the Exception propagated to the calling environment. The calling environment can be either the run time system or calling method. In the above example, the Exception occurred in divide() method,as there was no handling mechanism , the Exception propagated to the calling method- main().Again the main() method did not have any Exception handling,it went to the calling environment i.e runtime. java provides a default run time handler.When runtime Exception handler receives the Exception,it shows the stack trace and terminate the program.
Exceptions are encapsulated into object that extends the throwable class and object of java.lang.Exception class.All the Exceptions belong to Exception class which is a child of throwable class.
      |                                                                                                     |
 Exception                                                                                      Error(Unchecked)
|                        |
Checked       Unchecked
Checked Exception:
1. IOException
2. ClassNotFoundException
Unchecked Exception:
1. Arithmetic Exception
2. ArrayIndexOutOfBoundException

The base class Exception is defined here.An Exception object can make use of the below methods of the throwable class:
Method Description
String getMessage Returns the description of an Exception. Example- throwable.getMessage()
Void printStackTrace() Displays the stack trace (Mostly used in debugging) Example- throwable.printStackTrace()
String toString() returns a string containing a short description of the Exception Example- throwable.toString()

Popular Exception and Error Classes are:
Runtime Exception SubClasses Exception Sub Classes Error Sub Classes Error Sub Classes
ArithmeticException ClassNotFoundException ClassCirculatoryError AbstractMethodError 
ArrayOutOfBoundsException DataFormatException ClassFormatError
ArrayStoreException IllegalAccessException OutOfMemoryError
ClassCastException InstantiationException IllegalAccessError
IllegalArgumentException InterruptedException IncompatibleClassChangeError
IndexOutOfBoundsException NoSuchMethodException InstantiaonError
NegativeArraySizeException CloneNotSupportedException LinkageError
NullPointerException NoSuchFieldException NoClassDefFoundException
NumberFormatException InvocationTargetException NoSuchFieldError
SecurityException PropertyVetoException NoSuchMethodError
StringIndexOutOfBoundException ServerNotActiveException StackOverFlowError
UnknownServiceException UnknownHostException Throwable
IllegalThreadStateException  SocketException UnknownError
IllegalMonitorStateException  ProtocolException UnsatisfiedLinkError
EmptyStackException  InterruptedIOException VerifyError
NoSuchElementException MalformedURLException VirtualMachineError
IOException ThreadDeath
FileNotFoundException StackOverFlowError
EOFException InternalError  

Checked Exception:
Checked Exceptions should be either declared in the throws clause of an method or should be handled inside a try catch block.Exceptions and it's sub classes are checked Exception.Checked Exceptions are verified at compiletime and must be handled or thrown.They are also known as compile time Exceptions.These Exceptions should not be ignored at the time of compilation.An Exception if sub class of Exception but not RuntimeException becomes checked Exception.

File file=new File("path of the file");
if we try to compile the above code,we will get the following exception:
Unreported FileNotFoundException must be caught or declared to be thrown

Unchecked Exception:
Unchecked Exceptions are not mandatory to either declared or handled. They are ignored at compile time by java compiler.Errors and Runtime Exception and it's sub classes are unchecked Exception. RuntimeExceptions are used to indicate programming error such as logic errors or improper use of an API ,programming bugs etc.If we create our custom exception and extend to RuntimeException instead of Exception,our custom Exception becomes Unchecked. It is dangerous if we do not know what we are doing. Hence best practice is to make custom Exception extending to Exception.

int num[]={1,2,3}
This code will compile fine but fails at runtime.
Exception details:
Exception in Thread "main"

Error and its sub classes are used for serious errors from which programs are not suppose to recover.They are not at all Exceptions. Errors are generally ignored during compilation time.
Exp-out of memory error.
If compiler displays an error it will not create a .class file.While runtime error occurs,program will stop execution after displaying error message.

Why force Checked Exceptions thrown by a method to be caught but not Unchecked Exception?
Checked Exceptions thrown by a method are part of the public programming interface.Those who invokes the method must be aware of them and should  decide what to do with them.On the other hand, unchecked Exceptions are result of programming problem. It is usually not possible to recover from those problems.There could be numerous possibilities for Unchecked Exceptions,trying to cover all of them will reduce that code clarity.

Rule of Thumb while designing the public API that throws Exception:

  1. If the API user can take some meaningful action from the information available in the Exception object,We need to declare the Exception as checked.
  2. if the API user can not do anything meaningful after the Exception is thrown,We need to declare it as Unchecked Exception
Rule of Thumb with Exceptions Across Layers:
We need to make sure implementation of specific lower level exception should never propagate to higher levels(Low level Data access exception should not propagate to higher level like business level as it does not make any sense there)
Exception and Error Concept Simplified in Java Exception and Error Concept Simplified in Java Reviewed by Animesh Chatterjee on January 25, 2018 Rating: 5

No comments:

Powered by Blogger.