Java Handling Exceptions

In programming, we always encounter error inputs from users. Hence, what are we going to do when users' input encounter an error. This is what the chapter is about, handling different error situations. A java exception is an object that is created when an error occurs in a java program and java can't automatically fix the error. Each type of exception that can occur is represented by a different java handling exception class. Here are some typical ways of java handling expcetions:

*    IllegalArgumentException:    An incorrect argument is passed to a method

*    InputMismatchException:    The input doesn't match to the data type

*    ArithmeticException:    An illegal type of arithmetic operation, such as dividing by zero

*    IOException:    An I/O error is encountered

*    ClassNotFoundException:    A necessary class couldn't be found

There are many other exceptions than the one we listed, although as we learn more and more about java we would encounter more and more exceptions. In java, when an error occurs, an exceptions object is created, then java is said to have thrown an exception. The statement that caused the exception can be catch if it wants to, although it doesn't have to catch the exception if it doesn't want to. It can skip it and let others to catch it. If everyone skips the exception and does not catches it, the program will corrupt with nasty looking messages.

 

Java Catching Exceptions

Lets see how a basic form of catching an exception is like

try
{
    statements that can throw exceptions

}
catch (exception - type identifier)
{
    statements executed when exception is thrown
}
 

Here, we place the statements that might throw an exception within the try block. Then we catch the exception with a catch block. Lets observe a basic program on how to use try and catch.

 

Here, we have a division inside the try block. Then we catch the ArithmeticException, and it outputs " Can't divided by zero!! ." Notice, after the ArithmeticException, there is an e, it could be anything that one prefer.

Lets observe another example

 

Here we have import java.util.*; the statement includes all the util, and we need it because it includes InputMismatchException. If we don't import the statement, we will get an error when compiling the program, it would say something like InputMismatchException does not found. The idea of this program is the same thing, if the user enters anything else besides an integer, the program will print out " Please enter an integer".

 

Well! that is the basic idea behind exception handling, we will discuss more about file exception handling when we discuss how to open a .txt file.

 

 

  <Java 24><Home>