![]()
package diyitianxuexijava;
public class Test1{
private String sex;
//异常处理
public void setSex(String sex) throws Exception{
if(sex.equals("男")||sex.equals("女")) {
this.sex=sex;
}else {
throw new Exception("性别只能为男女");
//当使用或声明throw抛出异常时,必须对异常进行处理或声明
}
}
public static void main(String args[])
{
Test1 p=new Test1();
//这里的try,catch就是对p调用setSex方法的处理
try {
p.setSex("boy");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*try {
int a=10;
System.out.println(a/0);}
catch(Exception e) {
System.err.println("字母不能除以0");
System.out.println(e.getMessage());
e.printStackTrace();
//e.getMessage();
}
*/
}
![]()