Java Exception Handling

Exceptions in Java (try/catch/finally/throw):

Here is an exception example from my open source encryption app called EZcrypt:

if (noPaddingError) {

try {

encryptionCipher.init(Cipher.ENCRYPT_MODE, myKeySpec);

} catch (InvalidKeyException keyEx) {

System.out.println(“invalid key exception”);

noKeyError = false;

}

}

Ignore the encryption stuff and just concentrate on the try and catch, along with the InvalidKeyException keyEx. When you catch, you will catch an exception, and give it a name. Whatever name you want.

Something you can do with exceptions is to use the getMessage() method. For example:

try (something) {

//something that can cause an error goes here

} catch (Exception e) {

System.out.println(e.getMessage());

}

The class or function that exception handling code lies in must add throws to its declaration, such as the following example (a different example from my encryption app):

public void registerEvents() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException {

// removed for brevity

}

Some exceptions are very specific, such as InvalidKeyException. However, some are very generic, like Exception.

A common exception that beginner programmers will encounter is ArrayIndexOutOfBoundsException.

For example, if you make an array with a size of 3, that means the indices for its elements are 0, 1, and 2. But new programmers might forget to start counting with 0, and instead try to assign something to the array index of 3, which is out of bounds for the array with that size.

← Previous | Next →

Java Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *