代码拉取完成,页面将自动刷新
package ch6;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestEx {
public static void main(String[] args){ // part5 main方法抛出异常 throws Exception,实际编程中不要写。
// Part 1:异常出现示例
int [] arr = {1, 2, 3};
System.out.println(arr[3]);
//System.out.println(2/0);
/*try {
System.out.println(2/0);
} catch(ArithmeticException ae) {
System.out.println("系统正在维护中,请与管理员联系"); // good or not
// ae.printStackTrace();
}*/
// Part 2:抛出异常示例
/*TestEx ex = new TestEx();
ex.m(0);*/
/*try {
new TextEx().m(0);
} catch(ArithmeticException e ) {
System.out.println("出错了");
}*/
// Part 3: 必须处理的异常继承于Exception
/*
FileInputStream in = null;
try {
in = new FileInputStream("test.txt");
int b;
b = in.read();
while(b != -1) {
System.out.print(b);
b = in.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} */
// Part 4: try-catch-finally关系
TestEx te = new TestEx();
try {
new TestEx().f2();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void m(int n) throws ArithmeticException {
if (n == 0) {
throw new ArithmeticException("被除数为0");
}
}
void f() throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream("test.txt");
int b;
b = in.read();
while( b != -1) {
System.out.println((char)b);
b = in.read();
}
}
void f2() throws FileNotFoundException, IOException { //处理,或者继续抛出
f();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。