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.
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.
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.
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.
More Related questions...