Java / Exception
How do we handle more Than One Type of Exception using catch block in Java?
Using multiple catch blocks we may specify multiples exception to be handled in Java. For example, the below code handles both IOException and SQLException.
catch (IOException ioEx) { logger.log(ioEx); throw ioEx; catch (SQLException sqlEx) { logger.log(sqlEx); throw sqlEx; }
Although the above code handles multiple exceptions, we could notice that both blocks has same code and handling multiple exception sometimes lead to code duplication. Also in releases prior to Java 7, it is difficult to create a common method to eliminate the duplicated code because the exception variable has different types.
In Java SE 7 and later, multiple exception by a single catch block is introduced. This feature eliminates code duplication and reduce the possiblity to catch an overly broad exception.
The following example, which will execute in Java SE 7 and later, eliminates the duplicate code.
catch (IOException|SQLException exception) { logger.log(exception); throw exception; }
The catch clause specifies the types of exceptions that each block can handle, and each exception type is separated with a pipe delimiter (|).
Note that if a catch block handles more than one exception type, then the catch parameter is implicitly final i.e. the exception variable value cannot be changed within the catch block.
Dogecoin
! Earn free bitcoins up to $250 now by signing up.
Earn bitcoins upto $250 (free), invest in other Cryptocurrencies when you signup with blockfi.
Use the referral link: Signup now and earn!

Using BlockFi, don't just buy crypto - start earning on it. Open an interest account with up to 8.6% APY, trade currencies, or borrow money without selling your assets.

Join CoinBase
! We'll both receive $10 in free Bitcoin when they buy or sell their first $100 on Coinbase! Available in India also.
Use the referral Join coinbase!

Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.

Webull
! Receive free stock by signing up using the link: Webull signup.
More Related questions...