Sie sind auf Seite 1von 9

Exceptions in Java

by TREVOR PAGE on AUGUST 25, 2012

What are Exceptions in Java?

What do they look like in Java code?

When should I choose to use them?

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!

What are Exceptions in Java

Java has a system that allows you to handle exceptional circumstances in


code.
What do I mean when I say exceptional circumstances? Well, I mean that
when your code is running, things can go wrong. For example, lets say we
specify that we want Java to read some information from a file. We specify the
filename and we try to open the file. Well, what happens if that file doesnt
exist (perhaps it was moved from the expected location during the time that
the program was running). Well, the code will complain! Java will throw an
exception. If you told Java to open a file at a specific location (i.e.
C:\logs\aLogFile.txt) and that file doesnt exist, what the heck should the
code do now?!

Exception Handling in Java

Well, thankfully theres a way for us to do something in the event of a problem


in our code. Heres an example of how you would handle reading a file in Java:

MyProgram.java
package com.howtoprogramwithjava.runnable;

import com.howtoprogramwithjava.fileio.FileIO;

public class MyProgram


{
public static void main(String[] args)
{
FileIO fileIO = new FileIO("C:\\aFile.txt");
}
}

FileIO.java
package com.howtoprogramwithjava.fileio;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileIO


{
public FileIO (String filename)
{
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(filename));
String line = "";
while((line = br.readLine()) != null)
{
System.out.println("Reading line: " + line);
}
}
catch (FileNotFoundException e)
{
System.out.println("There was an exception! The file was not found!");
}
catch (IOException e)
{
System.out.println("There was an exception handling the file!");
}
}
}

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:

There was an exception! The file was not found!

This is because we specified a filename in the constructor of our FileIO class


and you likely dont have this file on your computer. So when the code tried to
find it, and it couldnt, it threw an exception!
Now lets try adding this file to your computer, please create an aFile.txt file
on your C:\ drive, and put the following content in it:

This is line 1 of the file


This is line 2

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!

More details about Exceptions in Java

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.

What happens if you dont use a try/catch?


This is a good question, what will happen if there is an exception thrown from
a particular line of code, but that line of code is not inside of a try/catch block?
An ugly error, thats what! Lets change our code so that instead of catching
the error and just outputting a console message, were-throw the exception.
package com.howtoprogramwithjava.runnable;

import java.io.IOException;

import com.howtoprogramwithjava.fileio.FileIO;

public class MyProgram


{
public static void main(String[] args) throws IOException // we need to add a throws
declaration here
{
FileIO fileIO = new FileIO("C:\\aFile.txt");
}
}
package com.howtoprogramwithjava.fileio;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileIO


{
public FileIO (String filename) throws IOException // we need to add a throws declaratio
here
{
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(filename));
String line = "";
while((line = br.readLine()) != null)
{
System.out.println("Reading line: " + line);
}
}
catch (FileNotFoundException e)
{
System.out.println("There was an exception! The file was not found!");
throw e; // this is our new code
}
catch (IOException e)
{
System.out.println("There was an exception handling the file!");
throw e; // this is our new code
}
}
}
So, what you should notice with the modified code above, is that we
added throw e; inside of the catch blocks. So, lets say that we get
a FileNotFoundException thrown inside of our try block of code. This will cause the
code to flow into the first catch block, this is because weve specified that the
first catch block is supposed to handle FileNotFoundExceptions. Youll also notice
that we assigned the FileNotFoundException to the variable name e. This is just a
coding convention in Java, you can name your exceptions whatever you
like! Anyway, like I said, the code will flow into the first catch block of code, it
will then output our console message stating the file was not found, then it will
re-throw the FileNotFoundException. Since there is no additional catchblock to
handle the re-thrown exception, we will get a nasty console error, it will look
like this:
Exception in thread "main" java.io.FileNotFoundException: C:\aFile.txt (The system

cannot find the file specified)

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.

When should I use Exceptions


Now that you have a better understanding as to what an exception is in Java,
the next topic iswhen to use exceptions.
Well, in our example above, we dont actually have a choice. Java makes is
mandatory to handle any I/O exceptions. This mandatory handling of
exceptions is governed by the FileReader class and
the BufferedReaders readLine() method. If you were to inspect the code of that
class and method, youll notice that both have a throws clause on their Class
and method declarations:
FileReader.java
public FileReader(String fileName) throws FileNotFoundException
{
super(new FileInputStream(fileName));
}

BufferedReader.java -> readLine method


public String readLine() throws IOException
{
return readLine(false);
}

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

Okay, so I could probably ramble on and on for hours on the topic of


exceptions in java, but instead I will stop here and allow this information to
sink in a little. The best thing you can do is to use my code examples in your
IDE, and run the code in debug mode to understand how the code flows. If you
dont know how to debug, check out the next post it features debugging uses
the code from this post to explain the process!

Share the love

Das könnte Ihnen auch gefallen