package ThrowsExceptionTest;
public class A{ private String name; public void setName(String name){
this.name = name;
} public String getName() throws MyException{
if(name==null||name==""){
throw new MyException("名字不能为空");
}
return this.name;
}
public String toString() throws MyException{
String s;
s = this.getName();
return s;
}
void ExceptionTwo(){
throw new NullPointerException("123");
}
public A() {
// TODO Auto-generated constructor stub
} /**
* @param args
* @throws MyException
*/
public static void main(String[] args) throws MyException {
A a = new A();
a.setName(null);
try{
System.out.println(a.getName());
}catch(NullPointerException e){
throw e;
}finally{
System.out.println("finally@@@");
}
a.ExceptionTwo();
}}class MyException extends Exception{
public MyException(String message){
super(message);
}
}
public class A{ private String name; public void setName(String name){
this.name = name;
} public String getName() throws MyException{
if(name==null||name==""){
throw new MyException("名字不能为空");
}
return this.name;
}
public String toString() throws MyException{
String s;
s = this.getName();
return s;
}
void ExceptionTwo(){
throw new NullPointerException("123");
}
public A() {
// TODO Auto-generated constructor stub
} /**
* @param args
* @throws MyException
*/
public static void main(String[] args) throws MyException {
A a = new A();
a.setName(null);
try{
System.out.println(a.getName());
}catch(NullPointerException e){
throw e;
}finally{
System.out.println("finally@@@");
}
a.ExceptionTwo();
}}class MyException extends Exception{
public MyException(String message){
super(message);
}
}
2. 非要抛出异常的话, 改个名字好了, myToString()...
Object类的toString方法没有抛出异常所以,子类重写toString时不能抛出异常。
public String toString()
没有任何抛出异常
所以你一个异常也不能抛
本身的java.lang.Object.toString()就不会抛出异常,所以重写也不会抛出异常
详细信息如下:
toString
public String toString()返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于: getClass().getName() + '@' + Integer.toHexString(hashCode())
返回:
该对象的字符串表示形式。