DEV Community

Cover image for 4.2 Exception handling in Java
Raghav Khanna
Raghav Khanna

Posted on

4.2 Exception handling in Java

In Java an exception is an event to indicate an error during the runtime of an application. So this disrupts the usual flow of the application’s instructions.

In general exceptions are thrown up in the call hierarchy until they get catched.

Alt Text

Checked Exceptions

Checked Exceptions are explicitly thrown by methods, which might cause the exception or re-thrown by methods in case a thrown Exception is not caught.

So when calling methods, which throw checked Exceptions the Exceptions have either to be caught or to be re-thrown

'''

public void fileNotFoundExceptionIsCaughtInside() {
try {
createFileReader();
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
}

public void fileNotFoundExceptionIsReThrown() throws FileNotFoundException {
createFileReader();
}

public void createFileReader() throws FileNotFoundException {
File file = new File("/home/Documents/JavaTraining.txt");

// creating a new FileReader can cause a FileNotFoundException
new FileReader(file);

}
'''
Checked Exceptions are used when an error can be predicted under certain circumstances, e.g., a file which cannot be found.

Runtime Exceptions

Runtime Exceptions are Exceptions, which are not explicitly mentioned in the method signature and therefore also do not have to be catched explicitly.

The most famous runtime exception is the NullPointerException, which occurs during runtime, when a method is invoked on an object, which actually is null.

'''
public void causeANullPointerException() {
String thisStringIsNull = getMessage(false);

// because the thisStringIsNull object is null
// this will cause a NullPointerException
thisStringIsNull.toLowerCase();

}

public String getMessage(boolean messageIsAvailable) {
if(messageIsAvailable) {
return message;
}

return null;

}

Alt Text

Top comments (0)