Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does throw new exception inside a catch work?

I have a snippet as follows:

try
{
   //blah!!
} 
catch(IOException e)
{
   throw new RuntimeException(e);
}

I do not understand how the above works? Will it catch an IOException and when it does that will it throw a RuntimeException? In that case the IOException will not have any meaning right? Some example would help.

like image 900
noMAD Avatar asked Jun 29 '26 00:06

noMAD


2 Answers

You're right about some assumptions, but you should go a bit deeper. Inside your try block, suppose one of your methods of your class throws this kind of exception IOException. So catch will work as way for you to treat this exceptional case. It's basically this. If you just throw your exception away using a RuntimeException, but as you did, wrapping your IOException in RuntimeException you won't lose it at all.

A normal use is in a higher level treat your exception. Here's a good tutorial about Exception Handling, please check: Best Practices for Exception Handling

like image 67
axcdnt Avatar answered Jul 01 '26 14:07

axcdnt


In this code the checked IOException becomes effectively unchecked. By passing the IOException into the RuntimeException you are chaining the 2 together.

like image 32
Reimeus Avatar answered Jul 01 '26 14:07

Reimeus