java异常处理

java异常处理
try-catch-finally
语法:
| **try{
执行过程中可能出现错误的代码
} catch(可能出现的异常类型 ){
异常处理方案
} catch(可能出现的异常类型 ){
异常处理方案
} catch(可能出现的异常类型 ){
异常处理方案
} | |

示例:求用户输入的两个数字的商
public static void main(String[] args) {
try {
int a = 3;
int b = 4;
int res = a / b;
System.out.println(res);
} catch (Exception e) {
System.out.println(“chu cuo le”);
}finally {
System.out.println(“yi ding hui zhixing de dai ma”);
}
}
示例:多catch
public static void main(String[] args) {
try {
new FileInputStream(“G:/aaa.txt”);
System.out.println(3 / 0);
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException”);
} catch (FileNotFoundException e) {
System.out.println(“FileNotFoundException”);
}
}

|**try-multi-catch
如果多种异常的处理方式是一样的,可以合并
语法:
try{
执行过程中可能出现错误的代码
} catch(可能出现的异常类型1 |可能出现的异常类型2 |可能出现的异常类型3 …){ 异常处理方案
} | |

示例:
public static void main(String[] args) {
try {
new FileInputStream(“e:/ZoomIt.exe”);
System.out.println(3 / 0);
} catch (ArithmeticException |FileNotFoundException e) {
System.out.println(“CUO LE”);
}
}**

try-with-resources
有异常且需要释放资源的简化写法
语法:
Try(待释放的资源的创建语句){ //创建资源时可能会抛出异常
执行过程中可能出现错误的代码
} catch(可能出现的异常类型1 |可能出现的异常类型2 |可能出现的异常类型3 …){
异常处理方案
}

示例:
public static void main(String[] args) {
try(FileReader reader = new FileReader(new File(“E:/data.txt”))😉{
char[] buf = new char[16];
int len = -1;
while((len = reader.read(buf)) != -1) {
String str = new String(buf,0,len);
System.out.println(str);
}
}catch (Exception e) {
// TODO: handle exception
}
}
示例:
public static void main(String[] args) {
try (FileReader reader = new FileReader(new File(“E:/data.txt”));
FileWriter writer = new FileWriter(new File(“E:/abc.txt”))😉 {
char[] buf = new char[16];
int len = -1;
while ((len = reader.read(buf)) != -1) {
String str = new String(buf, 0, len);
writer.write(str);
}
} catch (Exception e) {
System.out.println(“cuo le”);
}
}

抛出异常
示例1:
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader(new File(“E:/data.txt”));
char[] buf = new char[16];
int len = -1;
while((len = reader.read(buf)) != -1) {
String str = new String(buf,0,len);
System.out.println(str);
}
reader.close();
}

示例2:
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader(new File(“E:/data.txt”));
FileWriter writer = new FileWriter(new File(“E:/abc.txt”));
char[] buf = new char[16];
int len = -1;
while ((len = reader.read(buf)) != -1) {
String str = new String(buf, 0, len);
writer.write(str);
}
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值