import java.io.*;
class MyException extends Exception{
  private String reason;
  public MyException(String r){
    reason=r;
    }
  public String getReason(){
    return(reason);
    }
}
class Excp{
  private  String s;
  public Excp(String ss)throws MyException{    
  s=ss;
  if(s=="XYZ"){
      throw new MyException("This is a XYZ");
      }
  }
}
class Test_Excp{
  public static void main(String args[])throws Exception{
    
    byte buffer[]=new byte[255];
    System.out.println("Plz input s1:");
    System.in.read(buffer,0,255);
    String s1=new String(buffer);
    try{
      Excp e1=new Excp(s1);
      }
    catch(MyException e){
    System.out.println("ddfd");
      }
   }
}

解决方案 »

  1.   

    运行后没有捕捉到异常MyException,怎么回事
      

  2.   

    s=="XYZ"
    换成"XYZ".equals(s)
      

  3.   

    还有一个问题,怎么不能把main后面的抛出删掉呢,函数里不是已经捕捉了吗?
      

  4.   


    import java.io.*;class MyException extends Exception {
    private String reason; public MyException(String r) {
    reason = r;
    } public String getReason() {
    return (reason);
    }
    }class Excp {
    private String s; public Excp(String ss) throws MyException {
    s = ss;
    if (s.equals("XYZ")) {
    throw new MyException("This is a XYZ");
    }
    }
    }public class Test_Excp {
    public static void main(String args[]) throws Exception {
    System.out.println("Plz input s1:");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s1 = in.readLine();
    try {
    Excp e1 = new Excp(s1);
    } catch (MyException e) {
    System.out.println("ddfd");
    }
    }
    }
      

  5.   

    还有怎么不能把main后面的抛出删掉呢,函数里不是已经捕捉了吗?
      

  6.   

    用标准输入流录入的地方要改要好一些。或者改成如下:
    .....
        System.in.read(buffer,0,255); 
        String s1=new String(buffer).trim(); //那个Buffer含有无效的字符
    .................
      

  7.   

     in.readLine();时会抛出IOException异常的