Java习题
Java入门习题
Java入门习题(一)——对象导论
Java入门习题(二)——操作符、控制符
Java入门习题(三)——初始化
Java入门习题(四)——接口、继承和多态
Java入门习题(五)——内部类
Java入门习题(六)——数组
Java基础习题
Java基础习题(一)——集合
Java基础习题(二)——异常
1,请写出下列程序的运行结果
class Demo{
public static String output="";
public static void func(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){
func(0);
System.out.println(output);
func(1);
System.out.println(output);
}
}
参考答案:
134
13423
答案解析
finally块中的内容无论什么情况都会执行
2,请写出下列程序的运行结果
class Demo{
static void func() throws Exception{
try{
throw new Exception();
}finally{
System.out.println("B");
}
}
public static void main(String[] args){
try{
func();
System.out.println("A");
}catch(Exception e){
System.out.println("C");
}finally{
System.out.println("D");
}
}
}
参考答案:
B
C
D
3,请写出下列程序的运行结果
class Demo{
public static void main(String [] args){
try{
throw new RuntimeException();
}catch(Exception e){
System.out.println("exception");
}catch(RuntimeException e){
System.out.println("runtime exception");
}
}
}
编译失败,父类异常应在最后捕获,否则子类异常捕获代码块永远都不会执行
4,请写出下列程序的运行结果
class Demo(){
public static void show() throws Exception{
throw new Exception();
}
public static void main(String [] args){
try{
show();
System.out.println("A");
}catch(Exception e){
System.out.println("B");
}finally{
System.out.println("C");
}
System.out.println("D");
}
}
参考答案
B
C
D
5,请写出下列程序的运行结果
class Demo{
public static void func(){
try{
throw new Exception();
System.out.println("A");
}cacth(Exception e){
System.out.println("B");
}
}
public static void main(String [] args){
try{
func();
}catch(Exception e){
System.out.println("C");
}
System.out.println("D");
}
}
参考答案
编译失败,原因:throw 之后不能定义语句。
5