Publish Your Article Here

Java Exception Handling - Multiple Cache Blocks Examples

  • A single try block can have multiple catch blocks. This is required when the try block has statements that generates different types of exceptions.
  • If the first catch block contains the Exception class object then the subsequent catch blocks are never executed.
  • The last catch block in multiple catch blocks must contain the Exception class object. This is because, the java complier gives an error saying that the subsequent catch blocks haven't been reached. This is known as Unreachable code problem.

Multiple Cache Blocks Sample Code

package com.myjava.exceptions;


public class MyMultipleCatchBlocks {
    public static void main(String a[]){
        MyMultipleCatchBlocks mmcb = new MyMultipleCatchBlocks();
    public void execute(int i){
            if(i == 1){
            } else {
        } catch (NumberFormatException nfe){
            System.out.println("Inside NumberFormatException... "+nfe.getMessage());
        } catch (MalformedURLException mue){
            System.out.println("Inside MalformedURLException... "+mue.getMessage());
        } catch (Exception ex){
            System.out.println("Inside Exception... "+ex.getMessage());
    public int getIntValue(String num){
        return Integer.parseInt(num);
    public URL getUrlObj(String urlStr) throws MalformedURLException{
        return new URL(urlStr);

Example Output

Inside NumberFormatException... For input string: "7u"
Inside MalformedURLException... no protocol:

blog comments powered by Disqus

Other Exception Handling Examples

Knowledge Centre
wait Vs sleep methods
sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired.

wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block. The call to wait() releases the acquired lock.

About Author

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2015 by Nataraja Gootooru. All Rights Reserved.