Exceptions in Java
Exceptions in Java
These are the topics I wish to discuss in todays post! But, I also want to
address another issue in this post. I know at this point you must be yearning to
create a fully functional and practical Java program by now. So todays the day
that I wont hold anything back when it comes to the code. Today youll really
see how to program with Java So without further delay, heres the
content!
MyProgram.java
package com.howtoprogramwithjava.runnable;
import com.howtoprogramwithjava.fileio.FileIO;
FileIO.java
package com.howtoprogramwithjava.fileio;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
Wow! So thats a lot of code. Now, if you were to copy/paste this code into a
project that you create (remember to name the files appropriately, and place
them into the correct packages), youll notice that you get the following output
when you try to run the program:
Once youve done this correctly, and you re-run this Java program, you should
see the following output:
Reading line: This is line 1 of the file
Reading line: This is line 2
If you are able to see that in your console, then youve done it!
Now that youve seen the code for reading a file, and the exception handling
that goes along with it, lets talk more about the code. The most important
thing to note about exception handling is the following:
try
{
// insert code to execute here that may throw an exception
}
catch (Exception e)
{
// and exception WAS thrown, do something about it here!
}
This is called a try/catch block. Its designed so that if you put code between
the curly braces {} of the try block, then any exceptions that occur will make
the code flow jump into the catch block. If no exceptions occur, then the code
will flow through the entire try block, and skip the catch block of
code.
This concept of code flow is critical to understand, if you want to grasp what
exception handling is in Java. In my next post I will show you how to use the
debugger in Spring STS, and this will help you understand exactly how the
code flows.
import java.io.IOException;
import com.howtoprogramwithjava.fileio.FileIO;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at java.io.FileReader.<init>(FileReader.java:41)
at com.howtoprogramwithjava.fileio.FileIO.<init>(FileIO.java:15)
at com.howtoprogramwithjava.runnable.MyProgram.main(MyProgram.java:11)
This output is called a stack trace. It is Javas way to let the programmer
know that theres been an exception that was not handled, and thus the
execution stopped. This output will help the programmer figure out where the
exception occurred, and thus, give a clue to how it can be fixed/addressed.
Because Java has included those throws clauses, we are now forced to handle
those exceptions. So if we do not use a try/catch block (or specify
a throws clause on our methods that use this I/O code) well get an error in our
IDE telling us we need to do something! This error would like something like
this:
Now there are other times when its not mandatory that you use exception
handling in Java, but it may be beneficial. Examples of this are if you are
designing a software application that needs to follow certain business rules. In
order to enforce those business rules, you could create your OWN exception
class (by creating a new Class and extending the Exception Class) and throw
THAT exception if a certain condition is met. Lets say, for instance, you are
creating a webpage that has a user login feature. When the user tries to login
with a password that is incorrect, perhaps you would like to throw an
InvalidUserLoginException? The design of the system will be up to you, or
the architect of the system, but this is an option that Ive seen used before.
Bonus material
Theres one other aspect to the try/catch block that I didnt mention, and thats
the finallyblock. It looks like this:
try
{
// insert code to execute here that may throw an exception
}
catch (Exception e)
{
// and exception WAS thrown, do something about it here!
}
finally
{
// When the code flows out of the try or catch blocks, it
// will come here and execute everything in the finally block!
}
What!? Seriously, theres another aspect to this exception stuff! I know, but its
the last crucial concept youll need to understand before you can say you
understand exceptions in Java. As the code comments state, the finally block
will be executed after the code has either finished executing in the try block, or
in the catch block.
So whats the purpose of the finally block? Well, its normally used to clean
up after yourself. An example of this is trying to have your code talk to a
database (like MySQL/Oracle/MS SQL Server). Talking to a database is no
simple task, and it involves steps. The first step is to open a connection to
the database (very similar to opening a file like we did in this example). Well,
what if something goes wrong after weve opened the connection to the
database? We need to make sure we close the connection to the database,
otherwise well run into problems (which I wont example here as its currently
not in our scope of learning). The finally block allows us to do this closing
part. Since we can be confident that the code will ALWAYS flow into
the finallyblock after its gone through either the try or the catch, then we can
throw in our code to close the database connection in the finally block. Does
that make sense?
Note: For the sake of being complete, Ill mention that the finally block doesnt
necessarily execute immediately after the code flows past the try/catch block,
but it will eventually execute the code in the finally block so I wouldnt put
any code in the finally block that has any dependency on time/point of
execution.
Final words