Thursday, 22 August 2013

Understanding Exceptions and Errors

This post will cover very basic meaning and understanding of Exception and Error in java.

What is Exception?

Sometimes the program(code) we write does not behave the way we intent to. Java is designed to be simple. Hence Java developers provided exception handling from the very beginning. By Exception handling it is made sure that all the possible cases in your code which may led to unexpected behavior are handles.

How is Exception different from Error?

Exception as I mentioned previously is  unexpected behavior of your code. This statement is also applicable to Error but the difference being we can recover from Exception but we cannot recover from an Error. Error is fatal and will directly terminate your program and on the other hand Exceptions are situations that can be taken care of . They can be handled so that program can carry on it's execution.


   Consider a program in which you read some data from user store it in an array and then when user is finished entering data you write this data in a file. Now we know that when we have to write some data in a file it is very much possible that the files may not be present. This results in an Exception. But note that this situation is recoverable. We can specify a construct(we will get to it's syntax and technical aspect a bit later) that will help us catch this type of situation and figure out a way out of it. Possible way out would be inform user that the file is not present and ask him to provide a path for the same.

How decides whether some Exception can occur in curtain situation? Can we create our own custom Exception?

Java is an Object oriented programming language. There are objects and they have methods that are used to interact with other objects.  Exception and Error are also objects. We know Exceptions can occur while executing a particular method. So when we declare this method which we know can throw a known exception we simply state(in the methods signature) that whoever uses this method must handle the corresponding Exception. In fact in java your code will not compile unless you handle all the exceptions associated with the methods in the code you are compiling. So as far as our first question in concerned developers who write(code) a method also indicate the corresponding exceptions in the methods signature. Yes! we can create our own custom Exception. We can create our own function/methods that throw these Exception. Of course there are rules as of how can you achieve this in Java but none the less it can be very much done. 

Exception and Error Structure in Java

This is just to give a structural overview of Exception and Error in java. We will get to it's technicality is future posts.

t> UA-39527780-1 back to top