第七章
1.“程序中凡是可能出现异常的地方必须进行捕获或拋出”,这句话对吗?
不对
异常类型是RuntimeExecption或是其子类,程序方法可以对异常不做任何声明抛出或处理,直接交给调用该方法的地方处理,程序能编译通过,不会对可能产生异常的代码行给出提示。
2.自定义一个异常类,并在程序中主动产生这个异常类对象。
public class ClassText {
public static void main(String[] args) {
int radius ;
radius = -5;
try {
textThrow_Throws(radius);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序正常结束~");
}
private static void textThrow_Throws(int radius) throws Exception {
if ( radius < 0 ) {//半径正常大于0
throw new Exception();
}
}
3.借助JDK帮助,请列举发生NullPointerException异常的一些情况。
当应用程序试图在需要对象的地方使用 null 时,抛出该异常。这种情况包括:
调用 null 对象的实例方法。
访问或修改 null 对象的字段。
将 null 作为一个数组,获得其长度。
将 null 作为一个数组,访问或修改其时间片。
将 null 作为 Throwable 值抛出。
应用程序应该抛出该类的实例,指示其他对 null 对象的非法使用。
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("exception111");
}
//---------------------------------------------------------------------------
}
public void main(String[] args){
try{
aMethod();
}
catch(Exception e){
System.out.println("exception");
}
System.out.println("finished");
}
}
输出:exception000
exception111
finished
去黑体输出:exception111
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
8.阅读下面程序,TimedOutException为自定义异常,完成指定方法后面的部分。
public void method()throws TimedOutException
{
success= connect();
if(success == -1)
{
throw new TimedOutException();
}
}
第八章
3.String类型有什么特点?
1.一旦赋值,便不能更改其指向的字符对象
2.如果更改,则会指向一个新的字符对象
3.不能为null
4.String什么时候进行值比较,什么时候进行引用比较?
String A.equals(String B);进行值比较
string A == String B;进行引用比较
5.String与StringBuffer的区别是什么?如何相互转化?
String,字符串常量,不可变
StringBuffer是一个具有对象引用传递特点的字符串对象。
//数据类型由String转为StringBuffer
String s = “hello”;
StringBuffer sb = new StringBuffer(s);
//StringBuffer转换String
String str = sb.toString() ;