Throws
The developer is forced to wrap the code with try/catch.
/**
* Throws Exception
*
* Using throws Exception forces the developer ...
* to wrap the code with try/catch
* She will know that you are using a risky method
*/
package com.minte9.basics.exceptions;
public class Throws {
public static void main(String[] args) {
try {
A.check("correct");
A.check("wrong"); // OK for compiler
} catch (Exception e) {
System.out.print(
"Exception: " + e.getMessage() // Exception: Wrong value!
);
}
}
}
class A {
static boolean check(String s) throws Exception { // Look Here
if (s.equals("wrong")) {
throw new Exception("Wrong value!");
}
return true;
}
}
Multiple
A method can throw multiple exceptions.
/**
* Multiple exceptions
*
* A method can throw multiple exceptions
* Declare it, when you don't want to handle an exception
* The code inside finally block is always executed
*/
package com.minte9.basics.exceptions;
public class Multiple {
public static void main(String[] args)
throws NullPointerException { // Look Here
try {
test(-10); // Positive number required!
System.out.println(args[2]); // Index 2 out of bounds!
} 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");
}
}
}
Last update: 357 days ago