Package com.martinandersson.lesson03.branching

Source Code of com.martinandersson.lesson03.branching.TryCatch_Checked

package com.martinandersson.lesson03.branching;

import java.io.IOException;
import java.io.UncheckedIOException;

/**
* Demonstrates all checked exception, those that are not {@code RuntimeException}
* or a subclass thereof.
*
* @author Martin Andersson (webmaster at martinandersson.com)
*/
public class TryCatch_Checked {
    public static void main(String[] ignored) {
        // Does not compile without try-catch or redeclaration of throws clause:
//        start();
       
        try {
            start();
        }
        catch (IOException e) {
            System.out.println("Failed to open a file or something :'(");
           
            // Discouraged, but sometimes usefiul:
            throw new UncheckedIOException(e);
        }
    }
   
    private static void start() throws IOException {
        /*
         * This method do not handle the exception, we need to redeclare
         * the throws clause in our own method signature!
         */
        throwIOException();
    }
   
    private static void throwIOException() throws IOException {
        // Unchecked exception do not require client's to deal with them:
//        throw new RuntimeException("Unchecked!");
       
        // .. checked exceptions do:
        throw new IOException("Is a checked exception.");
    }
}
TOP

Related Classes of com.martinandersson.lesson03.branching.TryCatch_Checked

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.