Exceptions Part 1 – Basics

if an application doesn’t behave as it supposes, there is a way to let outside world know. this way is to raise an exception.

below is the exception hierarchy in java
since Exception itself is an object and to be raised they should be thrown, the need to extends from Objects class and then Throwable interface.

Objects|
+- Throwable (interface)         
          |
+ ----------------------------------+
|                                    Exception
|                      ---------------+---------------------
|                      |                                    |
Error                  RunTimeException                     rest of the Exceoptions
[counted as Checked]   [Checked Exceptions]                [Unchecked Exceptions]

Checked & Unchecked Exceptions

Checked and unchecked exceptions are the two main categories that java separated all the unintended status of application into.

Unchecked Exceptions is the category that technically JVM will take care of that and when they raise the application terminated and won’t get into a situation that users left in a limbo with no information. so we are developer don’t need to take care of them in our application.

Checked exceptions are the unintentional behaviour of the application that might not be our preferable and they needed to be handled by developers.

Method Stack & Exception:

when an checked exception happenes, it needs to be handled somewhere in code. so the matter is where and who needs to handle it. this only means, when in memory stack methods will be pushed in top of each other from buttom of stack to the place that throws the exception, anyone of these methods can be responsible for handling that exception. the only factor is which one make sense more to handles that.

quick notes: try -finally – normally to handle closing files or streams. or network sockets.

 

you can use something like below snippet in any part of your code. even in try nad finally block, for example you are trying to handle file related exceptions so you can catch it or not catch it and let callers method handles it.


public void myMethod() throws IOException{

// doing something with file streams

try{

//doing the rest of stuff

}finally{

//doing some cleaning if I need.

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s