PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   22-10-2021

Throws

p326 ! The developer is forced to wrap the code with try/catch.
 
/**
 * Using "throws Exception" forces the developer ...
 * to wrap the code with try/catch.
 * It will know that you are using a risky method.
 */

package com.minte9.basics.exceptions;

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

        try {
            myMethod("wrongValue"); // the compiler is OK
        } catch (Exception e) {
            System.out.print("Exception found!"); // Exception found!
        }
    }
    
    static void myMethod(String s) throws Exception {
        
        if (s.equals("wrongValue")) {
            throw new Exception();
        }
    }
}

... 13 lines
 

Finally

The code that is run regardless of an exception.
 
/**
 * The code inside finally block is always executed
 * (is an exception or not)
 */

package com.minte9.basics.exceptions;

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

        try {
            myMethod("myValue");
        } catch (Exception e) {
            System.out.println("Exception");
        } finally {
            System.out.println("Executed always!");
        }

        /*
            myValue
            Executed always!
        */
    }
    
    static void myMethod(String s) throws Exception {
        
        if (s.equals("wrongValue")) {
            throw new Exception();
        }

        System.out.println(s);
    }
}

... 19 lines
 

Multiple

p329 ! A method can throw multiple exceptions.
 
/**
 * A method can throw multiple exceptions.
 * If you don't want to handle an exception, you can declaring it.
 */

package com.minte9.basics.exceptions;

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

        try {

            test(-10);      
                // Exception: Positive number required!

            System.out.println(args[2]);
                // Exception: Index 2 out of bounds ... 

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

... 19 lines
 

Questions     github Basics
Regexp

        A B C D E F
🔔
1/4