Soni's Blog

An introduction to Exception-Oriented Programming

Exception-Oriented Programming is a technique that stands in contrast to checked exceptions. Like checked exceptions, it's built on the idea that errors should be checked. Unlike checked exceptions, it's built on the idea of delegating exception-related responsibilities.

For starters, exception-oriented programming relies heavily on run-time checking. In this manner, it is actually most similar to Rust's Result::unwrap. At the same time, it easily supports the ability to propagate the exceptions.

For example, let's say you want to rely on NullPointerException (NPE) in your API. In traditional Java, this is a terrible idea, because everything throws NPE if you forget to check against null somewhere. However, Exception-Oriented Programming works by simply wrapping the rest of your code and making sure it can't throw NPE. Or, in code:

This code will never throw NPE, and exemplifies the starting point for Exception-Oriented Programming. That is, the first step to Exception-Oriented Programming is to simply wrap your entire function in such a try-catch, and rethrow everything you care about as (in this case) RuntimeException.

Any code inside this try acts exactly like a Rust Result::unwrap. Unfortunately, this is the last time you'll see syntax this clean, because most programming languages (including Java) do not have syntactic support for Exception-Oriented Programming.

But we can still propagate exceptions. We just need to do so carefully, here's an example:

In this code, our method foo is never gonna throw NPE, except if, and only if, baz throws NPE. It's like our method has chosen to forego the ability to throw NPE itself, while granting baz the authority to do so (as in delegation of responsibilities).

And this is the key concept behind Exception-Oriented Programming. It's all about thinking with exceptions.

This is however fairly verbose, and to solve that, we would like to see a programming language with built-in support for the technique some day. That is, an Exception-Oriented Programming Language. We think it is a much better approach to error checking than Java's idea of checked exceptions.