Throws Exception

 
/**
 * To force an exception use 'throws Exception' in method definition.
 * The developer will know that you are using a risky method.
 * The developer is forced to wrap the code with try/catch.
 */

package com.minte9.basics.exceptions;

public class Throws_Exception {
    public static void main(String[] args) {

        try {
            check("wrong"); // Correct code (for compiler)
        } catch (Exception e) {
            System.out.println(e.getMessage());  // Wrong value exception!
        }
    }

    private static boolean check(String s) throws Exception { // Look Here
        
        if (s.equals("wrong")) {
            throw new Exception("Wrong value exception!");
        }
        return true;
    } 
    
}

Multiple Exceptions

 
/**
 * A method can throw multiple exceptions.
 * When you don't want to handle an exception, you can declare it.
 * The code inside finally block is always executed.
 */

package com.minte9.basics.exceptions;

public class Multiple_Exceptions {
    public static void main(String[] args) 
        throws NullPointerException { // Look Here

        try {
            test(-10); // Positive number required!
            
            String val = args[2]; // Index 2 out of bounds! 
            System.out.println(val);

        } catch (ArrayIndexOutOfBoundsException ex) { // Look Here
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            System.out.println("Always executed!");
        }
    }
        
    public static void test(int n) 
        throws Exception, ArrayIndexOutOfBoundsException {
        
        if (n < 0) {
            throw new Exception("Positive number required");
        }
    }
}






Questions and answers:
Clink on Option to Answer




1. To warn the compiler that you will use a risky method

  • a) use throws in method declaration
  • b) use throws in main

2. Throws Exception in method declaration

  • a) extend the Exception class
  • b) forces the developer to use try/catch

3. If you want to avoid Exceptions use

  • a) throws in main declaration
  • b) try/catch block

4. Which one is correct?

  • a) throws Exception("message");
  • b) throw new MyException("message");


References: