功能:通过命令行输入参数,如果不输入出参数就抛出自定义的异常
(系统里也有这个异常,但不想用系统自带的)
例:java Inheriting 123
java Inheriting //抛出自定义的异常
但现在有个问题就是,下面的程序不抛出自定义的异常,而只能抛出系统自带的异常。
请指点一下。谢谢。。class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}public class Inheriting {
public static void f(String s) throws MyException {
if (s=="")
throw new MyException();
} public static void main(String args[]) {
try {
String s="";
s=args[0];
f(s);
} catch(MyException e) {
//e.printStackTrace();
System.out.println("123");
}
}
} E:\>java Inheriting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Inheriting.main(Inheriting.java:20)
(系统里也有这个异常,但不想用系统自带的)
例:java Inheriting 123
java Inheriting //抛出自定义的异常
但现在有个问题就是,下面的程序不抛出自定义的异常,而只能抛出系统自带的异常。
请指点一下。谢谢。。class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}public class Inheriting {
public static void f(String s) throws MyException {
if (s=="")
throw new MyException();
} public static void main(String args[]) {
try {
String s="";
s=args[0];
f(s);
} catch(MyException e) {
//e.printStackTrace();
System.out.println("123");
}
}
} E:\>java Inheriting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Inheriting.main(Inheriting.java:20)
s=args[0];不给你一个数组越界才怪呢。:)
f(s);上面两行代码的执行顺序,谁在前谁在后?
也就是说还没等到f(s);语句被执行,
s=args[0];语句就已经抛出异常转移控制权了。
你觉得呢?:)
f(s);
改成
f(args[0]);
也是一样呀!
f(s);
和
f(args[0]);本质上是一样的,因为args[0]的计算结果作为参数传递给f()。
为避免数组越界异常,你可以在使用args数组之前先检查它的数组长度,
例如:if(args.length == 0){
s = "";
}
else
{
s=args[0];
}