472,355 Members | 1,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,355 developers and data experts.

An Introduction to Exceptions - Ch. 3

RedSon
5,000 Expert 4TB
Chapter 3: What are the most common Exceptions and what do they mean?
As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception.

In general, you can sort Exceptions into two groups: Checked and unchecked Exceptions. Checked Exceptions are checked by the compiler at compilation time. Most Exceptions, that you will work with to control the flow of your program will be checked Exceptions.
Unchecked Exceptions are thrown at runtime and often mean, that you've made a mistake somewhere but the compiler couldn't know that.
All unchecked Exceptions extend RuntimeException, while all checked Exceptions don't.

There are a few Exceptions, that you will get ever so often. I've tried to make a list of the most common ones and to explain, what you can do to find, where it comes from. You should always look at the message you get from the compiler or at runtime - it will give you the line, in which it encountered the error.
  • ArrayIndexOutOfBoundsException

    This Exception, as most of them do and all of them should, describes what has gone wrong very well - some Array index is out of the given bounds. So, for example, you have an Array like this
    Expand|Select|Wrap|Line Numbers
    1. int [] array = new int[3]
    and you are trying to access a nonexistent element, maybe like this
    Expand|Select|Wrap|Line Numbers
    1. array[3]
    This is incorrect, as arrays start with element 0.

    Often you get this error, when using a for-loop which runs to often. Check the given line and find out, why it's trying to find an element, that doesn't exist.

    The ArrayIndexOutOfBoundsException is a unchecked Exception.
  • ClassCastException

    If you encounter a ClassCastException, there is an invalid cast somewhere. For example, the following code throws a ClassCastException:

    Expand|Select|Wrap|Line Numbers
    1. public class Exceptions {
    2.     public static void main(String[] args) {
    3.         // Anything extends java.lang.Object directly or indirectly and is therefore an Object
    4.         Object testClass1 = new Class1("1");
    5.         Object testClass2 = (Class2) testClass1;
    6.     }
    7. }
    8.  
    9. class Class1
    10. {
    11.     String x;
    12.  
    13.     public Class1(String x)
    14.     {
    15.         this.x = x;
    16.     }
    17. }
    18.  
    19. class Class2
    20. {
    21.     int x;
    22.  
    23.     public Class2(int x)
    24.     {
    25.         this.x = x;
    26.     }
    27. }
    28.  
    It does so, as it can not cast a Class1 Object to a Class2 Object. If you have created Classes yourself, normally you will have to tell the compiler how to cast them to another Class yourself:

    Expand|Select|Wrap|Line Numbers
    1. public class Exceptions {
    2.     public static void main(String[] args) {
    3.         // Now we've defined the cast ourselves and don't need to define the new Objects as Objects.
    4.         Class1 testClass1 = new Class1("1");
    5.         Class2 testClass2 = testClass1.toClass2();
    6.  
    7.         // If we do want to define them as Objects, it would work like this:
    8.         Object testClass1_2 = new Class1("1");
    9.         Object testClass2_2 = ((Class1) testClass1_2).toClass2();
    10.     }
    11. }
    12.  
    13. class Class1
    14. {
    15.     String x;
    16.  
    17.     public Class1(String x)
    18.     {
    19.         this.x = x;
    20.     }
    21.  
    22.     public Class2 toClass2()
    23.     {
    24.         return new Class2(Integer.parseInt(x));
    25.     }
    26. }
    27.  
    28. class Class2
    29. {
    30.     int x;
    31.  
    32.     public Class2(int x)
    33.     {
    34.         this.x = x;
    35.     }
    36. }
    37.  
    The ClassCastException is a unchecked Exception.
  • ClassNotFoundException

    This means, that a certain class cannot be found. Normally this happens, when you compile classes and try to run them without having compiled other classes, which are needed. It can also mean, that the needed classes are compiled, however not up to date. Try recompiling everything you need.
  • FileNotFoundException

    When you try to access a File, it may not exist. This code will throw a FileNotFoundException:

    Expand|Select|Wrap|Line Numbers
    1. import java.io.File;
    2. import java.io.FileInputStream;
    3. import java.io.FileNotFoundException;
    4.  
    5. public class Exceptions {
    6.     public static void main(String[] args) throws FileNotFoundException {
    7.         File file = new File("hello.txt");
    8.         FileInputStream iStream = new FileInputStream(file);
    9.     }
    10. }
    11.  
    WARNING: Please don't have a main method, which throws Exceptions. This should only be done for demonstration purposes. Catch and handle the Exceptions instead. A better way to handle this kind of situation would be:

    Expand|Select|Wrap|Line Numbers
    1. import java.io.File;
    2. import java.io.FileInputStream;
    3. import java.io.FileNotFoundException;
    4.  
    5. public class Exceptions {
    6.     public static void main(String[] args){
    7.         try
    8.         {
    9.             File file = new File("hello.txt");
    10.             FileInputStream iStream = new FileInputStream(file);
    11.         }
    12.         catch(FileNotFoundException fnfe)
    13.         {
    14.             System.err.println(fnfe);
    15.         }
    16.     }
    17. }
    18.  
    The ClassNotFoundException is a checked Exception.
  • IOException: The Input-Output-Exception is an Exception, which is very commonly used. The FileNotFoundException is one these and can therefore be caught with:

    Expand|Select|Wrap|Line Numbers
    1. catch(IOException ioe) {
    2.    //...
    3. }
    4.  
    The following code will throw a IOException:

    Expand|Select|Wrap|Line Numbers
    1. public static void throwIOException() throws IOException
    2. {
    3.    try 
    4.    {
    5.        OutputStream oStream = new FileOutputStream(new File("")); 
    6.       oStream.close(); 
    7.       oStream.write(0); 
    8.    }
    9.    // The FileNotFoundException extends IOException - however to get a basic 
    10.    // IOException, we do this: 
    11.    catch(IOException fnfe) 
    12.    {
    13.       IOException ioe = new IOException(); 
    14.       ioe.initCause(fnfe);
    15.       throw ioe; 
    16.     }
    17. }
    18.  
    This is also an Example of two things:
    • A wrapped exception - the try-catch-block catches one exception and throws another. This can be very useful in some cases.
    • Creating a chained Exception. This means, the Exception carries information about where it comes from (i.e. the "FileNotFoundException"). The adding of this information is done with the line ioe.initCause(fnfe); and it can be retained with

      Expand|Select|Wrap|Line Numbers
      1. catch(IOException ioe) {
      2. {
      3.    System.err.println(ioe); 
      4.    System.err.println("Cause: " + ioe.getCause()); 
      5. }
      6.  
    The IOException is a checked Exception.
  • NullPointerException
    A NullPointerException is thrown, when an Object has been defined, but not declared when you try to access it. To use the last example again, this code will throw a NullPointerException:
    Expand|Select|Wrap|Line Numbers
    1. import java.io.File;
    2. import java.io.FileInputStream;
    3. import java.io.FileNotFoundException;
    4.  
    5. public class Exceptions {
    6.     public static File file;
    7.     public static void main(String[] args){
    8.         try
    9.         {
    10.             FileInputStream iStream = new FileInputStream(file);
    11.         }
    12.         catch(FileNotFoundException fnfe)
    13.         {
    14.             System.err.println(fnfe);
    15.         }
    16.     }
    17. }
    18.  
    Check, if you have declared the Object, which you are trying to use in the Line given with the exception.
    The NullPointerException is a unchecked Exception.
You may of course face an exception not mentioned in this list. Often, just checking the line mentioned by the Exception and thinking about the name of the exception leads you to the solution.

Back to chapter 2 or Continue to chapter 4
Attached Files
File Type: zip Chapter3.zip (1.5 KB, 162 views)
Dec 18 '07 #1
0 6363

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Cletis Tout | last post by:
http://www.codeproject.com/cpnet/introtomono1.asp Introduction to Mono - Your first Mono app By Brian Delahunty The first in a series of articles about Mono. This article explains how to...
14
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of...
12
by: Xah Lee | last post by:
Of Interest: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html Currently, this introduction introduces you to the graphics format of Mathematica, and two Java Applet...
2
by: Jeroen | last post by:
We are experiencing a tuff-to-debug problem ever since we introduced a WebBrowser control into our failry large application. I'm not sure if the problem description below contains enough details,...
5
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is...
0
by: r035198x | last post by:
Inheritance We have already covered one important concept of object-oriented programming, namely encapsulation, in the previous article. These articles are not articles on object oriented...
0
RedSon
by: RedSon | last post by:
Chapter 2: How to handle Exceptions When you call a program, sometimes you get a message about an Unhandled exception type. This means, that something throws (or might throw) an Exception, but the...
0
Nepomuk
by: Nepomuk | last post by:
Chapter 1: What is an Exception? Imagine, you want to write a program for calculating. You start, it works fine, you can add, subtract, multiply and divide. Then there's a question: What about the...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it so the python app could use a http request to get...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.