Copyright

Exceptions in Java: Definition & Example

Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

File not found! We see exceptions every day as they are a feature of any program or programming language. In this lesson, we'll cover Java exceptions/errors, and provide some examples and methods for handling them.

Error! Error!

What is an exception in Java? The short answer: An exception is an error. The long answer: An exception is an unscheduled, unplanned event that interferes with a program's processing.

When Java encounters an exception, it throws it. Unfortunately it doesn't throw it away. Instead, it throws it to the internal system of the computer (called the runtime system). Basically, Java gives up, and tosses the exception to the system in hopes that there's something there that can handle the error.

Exception Types

When an exception is thrown, Java most likely knows what type of exception it is: Java is a pretty smart programming language, because it has many exceptions already built in. The following exceptions are already known by Java:

Java Exception Description
ArithmeticException Dividing by zero
ArrayIndexOutOfBoundsException Trying to reference an item in an array but the index doesn't exist
ClassCastException Try to change a String object to a Double
NullPointerException Try to call an object that isn't there

Errors:

  • Divide by Zero
  • File Not Found
  • Array Index Out of Bounds

But this doesn't mean you are safe! This only means that Java knows what to display when your program crashes. If you do nothing to handle (catch) these exceptions, Java will nicely tell you that you've hit a File Not Found exception. But your program will still terminate!

If there is nothing to 'catch' this error, the program crashes. This type of exception is an unhandled exception. The code that handles the error is called the 'exception handler', and is the code that catches the exception. As we'll see in our code, the actual Java keywords are 'try' and 'catch'.

Java Classes

When we say that Java includes the exceptions in its code, it means that there is actually a Java class (think blueprint) for these known exceptions. There is a Throwable class (which lets Java throw the exception), from which comes the all-important Exception class.

In turn there is a whole slate of sub-classes that all inherit from Exception. These include the arithmetic (divide by zero), file, and array exceptions shown earlier.

A few examples of the different classes and subclasses
Java Throwable Example

Exceptions: Examples

Let's look at a couple of examples of exceptions. We'll start with the divide by zero error, since it can happen very easily in code that crunches numbers.

Divide By Zero

The following code will most likely result in a divide-by-zero error. Whenever the date is Thursday, the modifier is set to 0; but the total value is calculated by dividing the fees by the modifier. Although it may seem apparent after looking at it, divide-by-zero errors can lurk in your code. The best bet is to create an exception handler to catch the errors.

double fees = 50;
double modifier = .05;
double total;
String todaysDate = new String();
while(fees < 50) {
  if(todaysDate == "Thursday") {
   modifer = 0;
  }
total = fees / modifier;
}

Array Out Of Bounds

The following code will compile without issue. But when we run it, an exception will be thrown and the program terminates. In this example, we create an array of size five, but write a loop to cycle through the array 15 times.

//Array size = 5
int[] numbers = new int[5];
//loop past the last array item
for(int i = 0; i < 15; i++) {
 System.out.println(numbers[i]);
}

When we run the code, the following error is displayed:


Java array output error


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support