Exceptions in Java

Jinwon Park
2 min readFeb 4, 2022

What is Exceptions in Java?

Exceptions are unwanted or unexpected event that disrupts the normal flow of the program’s execution.

There are two types of exceptions in Java.

Checked Exception: Compile time exception. ex) IO Exception

Unchecked Exception: Runtime exception. ex) NullPointer Exception

Checked Exceptions are exception that forces developers to handle the exception before compile time(otherwise it will not compile), while the Unchecked Exceptions are left for the developers to handle.

So how do you handle Exceptions?

If some code within a method throws checked exception, the method should either handle it with try~catch, or specify the exception by using the throws keyword.

The code below shows the example of checked exception.

public void readFile() {
FileReader fr = new FileReader("./someTextFile.txt");
}

This will throw a compile time error: FileNotFoundException. We as a developer need to either handle or specify the case where the file is not found.

try ~ catch (handle)

To handle, we can simply block the code with try ~ catch.

public void readFile() {
try {
FileReader fr = new FileReader("./someTextFile.txt");
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
}

This way, we can add actions in catch block to handle cases where unwanted flow occurs.

throws keyword (specify)

Another way to handle exception is to use throws keyword. It specifies the exception, and rather than handling right away, it defers the handling part to the caller of the method.

public void readFile() throws FileNotFoundException{
FileReader fr = new FileReader("./someTextFile.txt");
}

This will leave the handling part to the method calling the readFile().

Knowing the difference of checked vs unchecked exception becomes important when we use @Transactional functionalities in Spring.

Spring doc states that transaction will roll back on Runtime Exception(Unchecked Exceptions) and Errors, but not on checked exception.

So, throwing checked exceptions such as IOException in transaction will not cause a roll back.

One other concept to be aware when using transactions is that, if you catch exception by try ~ catch, you need to throw Runtime Exception. Otherwise, it will not roll back.

@Transactional
void doAction() {
try {
action1(); // normal action
action2(); //let's say this causes runtime error
}
catch(Exception e){
logError(); // log error
// if you don't throw runtime exception here, it will NOT rollback
}
}

** It is also worth knowing that Spring JDBC and MyBatis will throw Runtime Exception, even though Exception message will show SQLException, which is a checked exception.

--

--