Tuesday, 3 January 2017

What you should know about Java Exceptions.



A Glimpse

 

Learning exception and exception handling is very crucial to a Java Programmer. If you’re a beginner and you’re wondering why is it that your program ended up crashing even if your code seems to be perfect with no typos and compilation error then this write up might be useful to you. In this write up, I will try to go through Java Exception Handling concepts and cover important things about it.



Before actually going into the write up, I am assuming that you have a basic understanding of OOPs and Java Fundamentals. You are encouraged to use a good Java IDE (NetBeans IDE, Eclipse, BlueJ etc.) so that you don't waste time on trivial things such as indentation, code completion, etc.

Let us begin…

Java exception handling is one of the most important concepts of Java programming. If you're a beginner, you should get a basic understanding of how Java exception works and how you can utilize it in your programming. To get a clear picture, let's understand what an exception means in general.

Exception

 

Exception is just a fancy word for “Runtime Errors”. These are the errors that occur during runtime or while executing the program. An example of such an error could be that memory could not be allocated to an object or some crucial file to execute your program doesn’t exist anymore. In these cases, though your code is error free yet your program will not run.
 
One more thing to note is that exception (runtime errors) itself is of two types. These are Checked Exceptions and Unchecked Exceptions. Let us discuss them in brief.
  •      Checked Exception is an exception that needs to be handled by the programmer. It is mandatory to handle the common issues that may be raised while executing the program. It also encourages the developers to stay ahead and provide an alternative solution to common issues. For example, let suppose you are opening a file that doesn’t exist at the specified folder. In this case, your program will compile successfully but will not execute and most likely will give FileNotFoundException
  •       Unchecked Exceptions are the exceptions that can’t be handled by the programmer. The compiler takes care of the issue. For example, suppose you create an array of 10 elements with index 0 to 9 and you are trying to store data at 15th position. The compiler will most probably be like “You wanted me to allocate memory for 10 elements and you want to store data at 15th position of the allocated space? YOU MAD BRO? I’m definitely raising an issue here”.  Well this is because that the position you wanted to store data at is out of the allocated space. 
With that being discussed, let us move to the concept of Exception Handling in Java. 

 Exception Handling

Java Exception handling is a simple mechanism for handling runtime errors. And yes, that’s that. It a simple mechanism to handle the above mentioned exceptions (and a lot more) so that your program does not ends up crashing. Java has a powerful set of exceptional handling features and tools to handle the run time errors. We shall discuss them one by one. 

The Throwable class :  The Standard Java Development Kit provides us many predefined classes to handle exceptions. Throwable is the parent class of all the exception classes .Throwable has two sub classes inheriting from it. These are the Exception class and the Errors class. We have already discussed exception. So what are errors for? Are exceptions and errors the same thing? Well, not exactly. Errors are program conditions that are not handled by programmers. For example, JVM errors can never be handled by the programmer. Garbage collector errors are also not handled using the Exception class. Exceptions on the other hand are handled by either the programmer or the compiler. The Class hierarchy is given below... 
Try, Catch and Finally Block : 

Try block is the block (set of curly braces) that contains the code that might raise a runtime error and prevents crashing up of your program. Let me generalize this complex definition with the help of a tip, “You basically put the code that might raise an exception in the try block”. I will explain the syntax and mechanism of try block after I explain the concept of catch block. 

Catch block is the block (set of curly braces) that contains the code that you want to execute when an exception takes place. This may include stuff like prompting some error message on the screen. The catch block generally takes an object of type Exception or its subclasses (as mentioned in the “The Throwable class” section)

Finally block is the block (set of curly braces) that contains the code that will be executed no matter the exception is raised or not. The finally block is used to ensure that the code runs despite the exception.

Syntax and mechanism of try and catch block…
 



try
{
            Statement(s);
}
catch(ExceptionObject)
{
            Statement(s);
}
finally
{
            Statement(s);
}



It is a good programming practice to put the statements that we want to execute in the try block and TRY to execute it. Suppose, if any exception occurs in the try block then the control of the program will be transferred to the catch block and the statements given in the catch block will be executed further and thereby preventing the crashing of the program.  So, the workflow is simple, if an exception (or runtime error) occurs in the try block, it raises an exception to the catch block and is handled accordingly.
Let’s see an example to understand further… 

First let us see what could happen if we do not use the concept of exception handling 


Output:


The program seems to have no compilation error at all but still it has crashed and an exception has occurred because the solution of x/y is infinity which is not an actual numerical value. Since it is not an actual value, the computer can’t handle it and runtime error shall be raised and the program is most likely to crash.

 


Now we shall use the concept of try and catch blocks to handle the exception and try to prevent our program from crashing. 

 
Output:


First the system will try to execute the code in the try block. Since an exception shall be raised because the solution of x/y is infinity which is not an actual value, the control of the program will be transferred to the catch block and further code in the catch block will be executed. 


   

One important thing to note is that at its core, a program is a set of instructions. To run properly, it should not have any logical, runtime, or syntax errors

We have discussed that whenever a program encounters any runtime error, an exception is raised. The exception object is then thrown by the program, which is handled by the exception handler (the catch block). Since everything in Java is an object, exceptions created by programs are also objects. These objects contain all the information regarding the type of exception. This is the reason why I have passed an exception object to the catch block. 



Conclusion

Java Exception handling mechanism are great way of handling exceptions. It ensures program integrity in any condition. Programmers should always try to use exceptions as it makes their code more reliable. Plus, the concepts of exception handling in Java is very much similar to the concepts of exception handling in Python or C# or any other modern programming language. So mastering Exceptional handling skills in Java strengthens your exception handling skills in any other languages as well. 

I would now like to end this write up by saying that this was not a tutorial post but a blog post and thus is not very detailed. It did not contain the concept of multiple catch blocks, throw and throws keyword. The concepts provided here are brief and encourages the readers to read even further about the exception handling features and to adopt a good programming practice. 

Happy Programming!
 


 
 

What you should know about Java Exceptions.

A Glimpse   Learning exception and exception handling is very crucial to a Java Programmer. If you’re a beginner and you’re w...