| |
6. 23. 6. catch块来处理java.lang.Exception |
|
All Java exception classes derive from the java.lang.Exception class.
When a method throws multiple exceptions, rather than catch all the exceptions, you can simply
write a catch block that handles java.lang.Exception: |
public class MainClass {
public static void main(String[] args) {
String input = null;
try {
String capitalized = capitalize(input);
System.out.println(capitalized);
} catch (Exception e) {
System.out.println(e.toString());
}
}
static String capitalize(String s) throws NullPointerException, AlreadyCapitalizedException {
if (s == null) {
throw new NullPointerException("Your passed a null argument");
}
Character firstChar = s.charAt(0);
if (Character.isUpperCase(firstChar)) {
throw new AlreadyCapitalizedException();
}
String theRest = s.substring(1);
return firstChar.toString().toUpperCase() + theRest;
}
}
class AlreadyCapitalizedException extends Exception {
public String toString() {
return "Input has already been capitalized";
}
}
|
|
|