public class TestEx {
public static void main(String[] args) {

try {
new TestEx().f2();
} catch (IOException e) {
e.printStackTrace();
}



TestEx te = new TestEx();
te.m(0);

try {
new TestEx().m(0);
} catch (ArithmeticException ae) {
ae.printStackTrace();
System.out.println("出错了");
}


void m(int i) throws ArithmeticException {
if(i==0) 
throw new ArithmeticException("被除数为0");
}

void f() throws FileNotFoundException , IOException {
FileInputStream in = new FileInputStream("myfile.txt");
    int b;
    b = in.read();
    while (b != -1) {
        System.out.print((char) b);
        b = in.read();
    }
}

void f2() throws IOException {
/*
try {
f();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
*/
f();
}

}我不太明白的是:void m(int i) throws ArithmeticException {
if(i==0) 
throw new ArithmeticException("被除数为0");
}
这个定义好了一个方法,可能出现ArithmeticException异常,但是
                  TestEx te = new TestEx();
te.m(0); 是什么意思?new TestEx();在TestEx后加个括号是调用了TestEx这个类的构造函数?不解~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
try {
new TestEx().m(0);
} catch (ArithmeticException ae) {
ae.printStackTrace();
System.out.println("出错了");
}
同样,这个new TestEx().m(0);怎么理解?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
还有这个try {
new TestEx().f2();
} catch (IOException e) {
e.printStackTrace();
}
new TestEx().f2();怎么理解?

解决方案 »

  1.   

    我不太明白的是:void m(int i) throws ArithmeticException { 
    if(i==0)  
    throw new ArithmeticException("被除数为0"); 

    这个定义好了一个方法,可能出现ArithmeticException异常,但是 
                      TestEx te = new TestEx(); 
    te.m(0); 是什么意思?new TestEx();在TestEx后加个括号是调用了TestEx这个类的构造函数?
    new TestEx();就是实例化,它确实调用构造方法,但不单单是构造方法,还有初始化参数,还有对父类的!就是创建一个TestEx对象,

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    try { 
    new TestEx().m(0); 这里就同等于TestEx t = new TestEx ();t.m(0);
    } catch (ArithmeticException ae) { 
    ae.printStackTrace(); 
    System.out.println("出错了"); 

    同样,这个new TestEx().m(0);怎么理解? 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    还有这个try { 
    new TestEx().f2(); //更上面一样
    } catch (IOException e) { 
    e.printStackTrace(); 

    new TestEx().f2();怎么理解?
      

  2.   

    new TestEx();就是实例化,它确实调用构造方法,但不单单是构造方法,还有初始化参数,还有对父类的!就是创建一个TestEx对象, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~我不太明白的是: TestEx();我们new 一个对象的时候不是TestEx te = new TestEX();这个是调用了class  TestEx的构造方法吗?楼上说的还有“还有对父类的!”是什么意思,TestEx没有继承别的类啊!