exceptions
Checked and Unchecked Exceptions example
In this example we shall show you how to use a checked and an unchecked exception. A checked exception is anything that is a subclass of Exception, except for RuntimeException and its subclasses. In order to use a checked and an unchecked exception we have followed the steps below:
- We have created a method,
void checkSize(String fileName)that creates a new File with a given String filename and throws an IOException if the filename length is too large. - We also create another method,
int divide(int x, int y)that divides two int variables and returns the result. - When using the two methods, the first one must be put in a
try-catchblock, whereas the second one can be used without being surrounded by thetry-catchblock. It is an unchecked exception, so it doesn’t require you to catch it.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.basics;
import java.io.File;
import java.io.IOException;
public class CheckedUncheckedExceptions {
public static void main(String[] args) {
// We must catch the checked exception - to test use an existing file!
try {
CheckedUncheckedExceptions.checkSize("testFile.txt");
} catch (IOException e) {
e.printStackTrace();
}
// The unchecked exception doesn't requires you to catch it
CheckedUncheckedExceptions.divide(1, 0);
}
/**
* This method throws a Checked Exception, so it must declare the
* Exception in its method declaration
*
* @param fileName given file name
* @throws IOException when the file size is to large.
*/
public static void checkSize(String fileName) throws IOException {
File file = new File(fileName);
if (file.length() > Integer.MAX_VALUE) {
throw new IOException("File size is too large!");
}
}
/**
* This method throws a RuntimeException.
* There is no need to declare the Exception in the method declaration
*
* @param x the dividend
* @param y the divisor
*
* @return the division result
* @throws ArithmeticException when arithmetic exception occurs (divided by zero)
*/
public static int divide(int x, int y) {
return x / y;
}
}
This was an example of how to use a checked and an unchecked exception in Java.
