i

JAVA Complete Course

Throw, Throws and Finally

We have already touched the catching and handling exceptions in catch block but sometimes we also don’t need to take care of it and declare that some method might throw an exception. Another case is, when we will catch any exception and throw another one, or if we have some custom validation and if this validation fails, then we want to throw any custom exception (We will touch custom exceptions in next chapter). 

Another keyword in java is finally. This is a block which always executes. We can have following combinations: try-catch-finally, try-finally. If we have a finally block, it does not matter if exception happens or not, it will run anyway. Let’s see an example of finally block.

 A screenshot of a cell phone

Description automatically generated

Now let’s see an example when exception won’t happen and finally will execute:

A screenshot of a cell phone

Description automatically generated

Throw is a keyword which is used to throw any exception we want to happen. It can be any custom exception or general one. For example, let’s imagine situation that we have a class with the method divide. If our divisor will be zero, we need to throw RuntimeException with custom message instead of ArithmeticException (which happens automatically).

A screenshot of a cell phone

Description automatically generated

As we see in the first example we have normal result and in the second case, when divisor is equal to zero, we have RuntimeException instead of ArithmeticException.

Throws is the declaration in method signature that our method can have part of code, which can cause any exception and calling our method in some cases can cause throwing this exception. It happens when we have checked exceptions. As I mentioned in the very beginning checked exceptions must be handled in try-catch block or thrown. Let’s see an example when we want to read some information from file and as I/O throws checked exceptions and we don’t want to handle them, let’s declare it in method signature.

A screenshot of a cell phone

Description automatically generated