Encapsulating Try-Catch Statements

One of the things I enjoy the most in programming is to identify patterns, understand in a high-level what is being done or what is intended, and to abstract that into a contained solution.

I have created this repository, NunoAlexandre/abstractions, where I will be committing some examples of such abstractions, both in a way of exercising, to have fun and potentially to help someone.

Some languages, like Lisp, are highly malleable but Java is not. There are no macros and no way to change or extend the compiler in order to improve the core of the language.

But there is still some hope and some ways to improve it.

Try-Catch

Having said all above, what is a Try-Catch all about?
First, it is a very procedural-oriented thingy.
It defines two blocks, the try block and the catch.
And within the try block we place statements, from which one or more might fail, and in the catch, we handle those potential failures.

So we start by creating a variable without initializing.
Then we try to assign some value to it, which might cause an exception.
If it actually does cause an exception, we handle it.

Abstracting

Having that understanding, we can abstract it and encapsulate it. Although that in the end of the line, the code is the same, the fact that it is encapsulated and contained is already a better solution.
A criminal outside the jail or inside is still a criminal, but does less harm to the society. That’s how I see this.

It is important to also identify other possible cases:

where we want to get a value from somewhere

where we want to execute a statement, or another one in in the case when an exception arises.

where we want to execute a statement or another one in the case when an exception arises but feeding it with the exception.