RedSon 5,000
Recognized Expert Expert 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 NullPointerExce ption or ArrayIndexOutOf BoundsException. 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 RuntimeExceptio n, 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. - ArrayIndexOutOf BoundsException
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 - int [] array = new int[3]
and you are trying to access a nonexistent element, maybe like this
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 ArrayIndexOutOf BoundsException is a unchecked Exception.
- ClassCastExcept ion
If you encounter a ClassCastExcept ion, there is an invalid cast somewhere. For example, the following code throws a ClassCastExcept ion: -
public class Exceptions {
-
public static void main(String[] args) {
-
// Anything extends java.lang.Object directly or indirectly and is therefore an Object
-
Object testClass1 = new Class1("1");
-
Object testClass2 = (Class2) testClass1;
-
}
-
}
-
-
class Class1
-
{
-
String x;
-
-
public Class1(String x)
-
{
-
this.x = x;
-
}
-
}
-
-
class Class2
-
{
-
int x;
-
-
public Class2(int x)
-
{
-
this.x = x;
-
}
-
}
-
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: -
public class Exceptions {
-
public static void main(String[] args) {
-
// Now we've defined the cast ourselves and don't need to define the new Objects as Objects.
-
Class1 testClass1 = new Class1("1");
-
Class2 testClass2 = testClass1.toClass2();
-
-
// If we do want to define them as Objects, it would work like this:
-
Object testClass1_2 = new Class1("1");
-
Object testClass2_2 = ((Class1) testClass1_2).toClass2();
-
}
-
}
-
-
class Class1
-
{
-
String x;
-
-
public Class1(String x)
-
{
-
this.x = x;
-
}
-
-
public Class2 toClass2()
-
{
-
return new Class2(Integer.parseInt(x));
-
}
-
}
-
-
class Class2
-
{
-
int x;
-
-
public Class2(int x)
-
{
-
this.x = x;
-
}
-
}
-
The ClassCastExcept ion is a unchecked Exception.
- ClassNotFoundEx ception
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.
- FileNotFoundExc eption
When you try to access a File, it may not exist. This code will throw a FileNotFoundExc eption: -
import java.io.File;
-
import java.io.FileInputStream;
-
import java.io.FileNotFoundException;
-
-
public class Exceptions {
-
public static void main(String[] args) throws FileNotFoundException {
-
File file = new File("hello.txt");
-
FileInputStream iStream = new FileInputStream(file);
-
}
-
}
-
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: -
import java.io.File;
-
import java.io.FileInputStream;
-
import java.io.FileNotFoundException;
-
-
public class Exceptions {
-
public static void main(String[] args){
-
try
-
{
-
File file = new File("hello.txt");
-
FileInputStream iStream = new FileInputStream(file);
-
}
-
catch(FileNotFoundException fnfe)
-
{
-
System.err.println(fnfe);
-
}
-
}
-
}
-
The ClassNotFoundEx ception is a checked Exception.
- IOException: The Input-Output-Exception is an Exception, which is very commonly used. The FileNotFoundExc eption is one these and can therefore be caught with:
- catch(IOException ioe) {
-
//...
-
}
-
The following code will throw a IOException: - public static void throwIOException() throws IOException
-
{
-
try
-
{
-
OutputStream oStream = new FileOutputStream(new File(""));
-
oStream.close();
-
oStream.write(0);
-
}
-
// The FileNotFoundException extends IOException - however to get a basic
-
// IOException, we do this:
-
catch(IOException fnfe)
-
{
-
IOException ioe = new IOException();
-
ioe.initCause(fnfe);
-
throw ioe;
-
}
-
}
-
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 "FileNotFoundEx ception"). The adding of this information is done with the line ioe.initCause(f nfe); and it can be retained with
-
catch(IOException ioe) {
-
{
-
System.err.println(ioe);
-
System.err.println("Cause: " + ioe.getCause());
-
}
-
The IOException is a checked Exception.
- NullPointerExce ption
A NullPointerExce ption 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 NullPointerExce ption: -
import java.io.File;
-
import java.io.FileInputStream;
-
import java.io.FileNotFoundException;
-
-
public class Exceptions {
-
public static File file;
-
public static void main(String[] args){
-
try
-
{
-
FileInputStream iStream = new FileInputStream(file);
-
}
-
catch(FileNotFoundException fnfe)
-
{
-
System.err.println(fnfe);
-
}
-
}
-
}
-
Check, if you have declared the Object, which you are trying to use in the Line given with the exception.
The NullPointerExce ption 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 0 6489 Sign in to post your reply or Sign up for a free account.
Similar topics |
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 install Mono and shows how to compile your first Cross Platform
application.
|
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 contents, use the "Bookmarks" tab in Adobe
Acrobat.
Comments, corrections, praise, nits, etc., are still welcome!
|
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 utilities that allows you to view them
with live rotation in a web browser. Also, it includes a introductory
tutorial to POV-Ray.
|
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, so if I need to
elaborate on something please ask for it.
We have a UserControl with a WebBrowser on it. This UserControl is
instantiated a few...
|
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 JDK 6 downloadable from
http://java.sun.com/javase/downloads/index.jsp.
I will be using JDK 5(update 8)
| |
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 programming but on Java programming but I will cover all the important aspects of object oriented programming as Java has full support for object-oriented...
|
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 compiler doesn't know, what to do then.
You can deal with this in two different ways:
Throw the Exception further (pass it on to some other...
|
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 division by zero?
Say, your division method looks like this:
public double div(double a, double b)
{
return a/b;
}
You try:
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |