≡ Menu

Exceptions in Java

Java ExceptionWhat 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 today’s 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 today’s the day that I won’t hold anything back when it comes to the code. Today you’ll really see how to program with Java 😉 So without further delay, here’s 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, let’s 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 doesn’t 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 doesn’t exist, what the heck should the code do now?!

Exception Handling in Java

Well, thankfully there’s a way for us to do something in the event of a problem in our code. Here’s 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 that’s 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), you’ll 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 don’t have this file on your computer. So when the code tried to find it, and it couldn’t, it threw an exception!

Now let’s 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 you’ve 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 you’ve done it!

More details about Exceptions in Java

Now that you’ve seen the code for reading a file, and the exception handling that goes along with it, let’s 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. It’s 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 don’t 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, that’s what! Let’s change our code so that instead of catching the error and just outputting a console message, we re-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 declaration 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, let’s 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 we’ve specified that the first catch block is supposed to handle FileNotFoundExceptions. You’ll 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 catch block 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 Java’s way to let the programmer know that there’s 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 is when to use exceptions.

Well, in our example above, we don’t 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 BufferedReader‘s readLine() method. If you were to inspect the code of that class and method, you’ll 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) we’ll get an error in our IDE telling us we need to do something! This error would like something like this:

Exceptions in Java

Now there are other times when it’s 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. Let’s 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 I’ve seen used before.

Bonus material

There’s one other aspect to the try/catch block that I didn’t mention, and that’s the finally block. 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, there’s another aspect to this exception stuff! I know, but it’s the last crucial concept you’ll 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 what’s the purpose of the finally block? Well, it’s 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 we’ve opened the connection to the database? We need to make sure we “close” the connection to the database, otherwise we’ll run into problems (which I won’t example here as it’s 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 finally block after it’s 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, I’ll mention that the finally block doesn’t 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 wouldn’t 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 don’t 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

That ends today’s Java tutorial on how to program with Java, I hope you enjoyed it and found it to be useful 🙂 If you did, I encourage you to click the like/tweet/g+/stumble upon links on the left hand side of your screen so others will be able to benefit from this content. This website is still in its infancy and I would love to get the word out that it exists! To my readers who do this on every one of my posts, THANK YOU so much, I’m very happy that you guys are so excited about my Java tutorials!

Take care everyone 🙂

{ 17 comments… add one }

  • Gerry August 26, 2012, 3:28 pm

    another great tutorial..thanks 🙂

  • Murali August 26, 2012, 11:43 pm

    Nice Tutorials…Thanks.

  • chatu August 27, 2012, 2:19 am

    Great Post… Simple and Short…

  • Andrew P August 27, 2012, 1:15 pm

    I think it would good to expand on this topic some of the best practices concerning how to handle exceptions. Or at least talk about the trade-offs. For example: either handle the exception or throw the exception, but not both.

  • Ayyapillai August 31, 2012, 3:29 am

    Thanks for your grateful Java Tutorial informations.

  • ayalsew September 3, 2012, 4:25 am

    nice tutor

  • Jesse September 10, 2012, 9:01 pm

    These tutorials are insanely useful. Thanks again for your time in putting these together.

    • Trevor Page September 11, 2012, 8:33 am

      My pleasure Jesse, thanks for following along on Facebook! If you have any questions about the material, feel free to ask 🙂

      Trevor

  • azerty November 15, 2012, 10:46 am

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;

    class Creation_fichier
    {
    public static void main(String[] argv) throws IOException
    {
    File fichier ;
    fichier = new File(“C:\fichier.txt”);
    PrintWriter out ;
    out = new PrintWriter(new FileWriter(fichier));
    out.write(“Bonjour”) ; //écris bonjour dans le fichier
    out.println() ; //fais un retour à la ligne dans le fichier
    out.write(“Comment allez vous”) ; //écris dans le fichier
    out.close() ; //Ferme le flux du fichier, sauvegardant ainsi les données.

    }

    }

    Quand je l’execute j aurais :

    Exception in thread “main” java.io.FileNotFoundException: C: ichier.txt (La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:212)
    at java.io.FileOutputStream.(FileOutputStream.java:165)
    at java.io.FileWriter.(FileWriter.java:90)
    at Creation_fichier.main(Creation_fichier.java:13)

    aider moiii :'((((

    • Trevor Page November 15, 2012, 12:44 pm

      fichier = new File(“C:\\fichier.txt”);

      You need two backslashes when you try to to a backslash in a String. This is because a backslash (\) is used as an escape character.

  • Durim March 31, 2013, 7:05 pm

    Hi Trevor!

    Thanks for this tutorial!
    I don’t understand the difference between keywords “throws” and “throw” ?!
    Can you explain these to me!
    thank you!

    • Trevor Page April 8, 2013, 8:25 pm

      throw: is used when you are working within a method and you wish to actually throw an exception. ie. throw new IllegalArgumentException
      throws: is used only in method signatures to specify that that particular method will be throwing a particular exception type. ie. public void getUser() throws IllegalArgumentException

      These two cannot be interchanged… so you can never say throw in a method signature, and you can never say throws inside of the body of a method.

  • Lee March 3, 2015, 9:52 pm

    Hi Trevor,

    remember to name the files appropriately, and place them into the correct packages – i have no idea how to name the files appropriately and where to place them into the correct packages.

    i just opened a new java project and pasted the code to run it and it ran some other project i had done with while loops.

    thanks Lee

  • jyoti sankpal October 29, 2015, 1:53 pm

    Develop program to find the highest score stored in the file “SCORE.DAT”
    plz help to solve this program

  • Kevin Macaringue November 10, 2015, 4:26 pm

    Very simple and well written tutorial for Java. Thanks a lot!

  • Sarapaul January 18, 2017, 4:30 am

    Great step you have define it is really helpful for all developer making a website on javascript

  • 86Andreas August 20, 2017, 6:04 pm

    I have noticed you don’t monetize your blog, don’t waste your
    traffic, you can earn additional cash every month because you’ve
    got high quality content. If you want to know how to make extra money,
    search for: best adsense alternative Wrastain’s tools

Leave a Comment

Next post:

Previous post: