1.程序中凡是可能出现异常的地方必须进行捕获或抛出”,这句话对吗
不对,异常分为RuntimeException和非Runtime异常
**RuntimeException或其子类:**程序方法可以对异常不做任何声明抛出或者处理,直接交给调用该方法的地方处理,程序能编译通过,不会对可能产生异常的代码行给出提示,例如空指针异常,main()方法没有进行任何声明与处理,会直接交给调用main()方法的Java虚拟机进行处理(隐式抛出),当异常发生时,虚拟机会根据异常的类型,产生相应的异常对象,程序中应对这些异常对象进行处理。
**非Runtime异常:**例如调用readline()方法可能会发生IOException异常,它和RuntimeException是平行类,所以不能隐式抛出,需要进行捕获或者显式抛出处理。
2.自定义一个异常类,并在程序中主动产生这个异常类对象
class SelfException extends Exception{
SelfException(String msg){
super(msg);
}
}
class Person{}
public class test{
public static void main(String[] args){
int a=10,b=10;
try{
testException(a, b);
}
catch(SelfException e){
e.printStackTrace();
}
}
public static void testException(int a,int b) throws SelfException{
if(a==b){
throw new SelfException("a==b");
}
}
}
/**结果:
SelfException: a==b
at test.testException(test.java:20)
at test.main(test.java:11)
*/
3.借助JDK的帮助,请列举发生NullPointerException异常的一些情况。
调用一个null对象的实例方法。
访问或修改null对象的字段。
将null作为一个数组获取其长度。
将null作为一个数组访问或修改其时间片。
将null作为throwable值抛出。
4.不执行程序,指出下面程序的输出结果;如果将黑体代码去掉,写出输出结果;如果再将斜体代码去掉,写出输出结果。
public class test {
public static void aMethod() throws Exception{
try {
throw new Exception();
}catch(Exception e) { 黑体
System.out.println("exception000");
}
finally { 斜体
System.out.println("finally111");
}
}
public static void main(String[] args) {
try {
aMethod();
}catch(Exception e) {
System.out.println("exception");
}
System.out.println("finished");
}
}
异常都是对象,try catch 处理异常后则不会抛出异常
运行结果:
exception000
finally111
finished
运行结果:
finally111
exception
finished
运行结果:
exception000
finished
5.不执行程序,指出下面程序的输出结果。
public class test{
public static String output="";
public static void foo(int i) {
try {
if(i==1) {
throw new Exception();
}
output+="1";
}catch(Exception e) {
output+="2";
return;
}finally {
output+="3";
}
output+="4";
}
public static void main(String[] args) {
foo(0);
foo(1);
System.out.println(test.output);
}
}
运行结果:13423
看来尽管try或catch语句块中有return,还是会执行finally语句块。看到了合理的解释是,在try中执行到return语句时,不会真正的return,即只是会计算return中的表达式,之后将结果保存在一个临时栈中,接着执行finally中的语句,最后才会从临时栈中取出之前的结果返回。finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。
8.阅读下面程序,TimeOutException为自定义异常,完成指定方法后面的部分
class TimedOutException extends Exception{
TimedOutException(String msg){
super(msg);
}
}
public class test{
public static int succuss;
public static int connect(int time){
if(time>24){
return -1;
}else{
return time;
}
}
public static void method(int time)throws TimedOutException{
succuss=connect(time);
if(succuss==-1){
throw new TimedOutException("time="+time);
}
}
public static void main(String[] args){
try{
method(25);
}catch(TimedOutException e){
e.printStackTrace();
}
}
}
/**结果:
TimedOutException: time=25
at test.method(test.java:19)
at test.main(test.java:24)
*/