异常处理
程序员查错网站http://stackoverflow.com/
程序异常处理关键字:try、catch、finally、throw、throws
1、异常的处理流程;
2、异常的处理格式;
3、异常处理的模型。
//程序异常
public class Day14 {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println("运行"+(10/0));
}catch (ArithmeticException e){
e.printStackTrace();
}
System.out.println("结束");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ClYbTZuG-1633234291620)(C:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-20210925115311307.png)]
//程序异常
public class Day14 {
public static void main(String[] args) {
System.out.println("开始");
try {
System.out.println("运行"+(10/0));
}catch (ArithmeticException e){
e.printStackTrace();
}finally {
System.out.println("finally");
}
System.out.println("结束");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uLGuixe2-1633234291621)(C:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-20210925115424338.png)]
class MyMath{
//此处明确告诉用户该方法上会有异常
public static int div(int x,int y)throws Exception{
return x/y;
}
}
public class Test21 {
public static void main(String[] args) {
try {
System.out.println(MyMath.div(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5XMPk6ox-1633234291622)(C:UsersLenovoAppDataRoamingTyporatypora-user-imagesimage-20210925122123642.png)]
//程序员查错网站http://stackoverflow.com/
//自定义错误
class AddException extends Exception{
public AddException(String msg){
super(msg);
}
}
public class Test23 {
public static void main(String[] args) throws Exception{
if ((10+20) == 30){
throw new AddException("错误的相加操作!");
}
}
}
== 30){
throw new AddException(“错误的相加操作!”);
}
}
}



