Head First Java: Chapter-11 summary

Risky Behavior

Tharaka Dissanayake
3 min readJul 18, 2022

What happens when a method we want to call is risky? So, in that case, we need to write code handling the failure. The exception is how we take the Risk in a method we didn’t write. For example, a method wants a file on the memory to run it, but that file does not exist on the memory. Then what will happen? It is a risky code. So we need to handle that incident.

We can use the try-catch block to handle risky codes.

If we wrap the risky code in something called a try/catch, the compiler will relax. A try/catch block tells the compiler that you know an exceptional thing could happen in the try block. So compiler must prepare to handle it. But the compiler knows how to handle it. Exceptions can be referred to polymorphically.

When we call the risky method, two things can happen. The compiler can run the risky method without struggling, or that code block may occur struggle when it runs.

If it can be a success also, it can be a fail. Finally, we want to do other things without breaking the execution flow. So we can use the code block finally for it. Finally, the block is run the final.

For example, If we want to bake a cake, we must turn on the oven. When it turns on, there can be faults, so we need to catch them. However, if the cake is baked successfully or not, we must turn off the oven. It can be represented using with try-catch-finally block as follows.

A method can throw one or more exceptions. The compiler will ensure to handle all the checked exceptions thrown by the method. So we need to catch all the thrown exceptions within the cath-blocks.

An earlier paragraph mentioned that Exceptions could be referred to polymorphically. So like all good objects. we can draw an example hierarchical tree of exceptions like below.

--

--