这篇文章主要介绍了java基础异常处理代码及原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

创新互联公司主打移动网站、成都网站设计、成都做网站、网站改版、网络推广、网站维护、域名与空间、等互联网信息服务,为各行业提供服务。在技术实力的保障下,我们为客户承诺稳定,放心的服务,根据网站的内容与功能再决定采用什么样的设计。最后,要实现符合网站需求的内容、功能与设计,我们还会规划稳定安全的技术方案做保障。
异常的定义:中断了正常指令流的事件。
try..catch..finally结构:
class Test{
public static void main(String[] args){
System.out.println(1);
try{
System.out.println(2);
int i = 1 / 0;
System.out.println(3);
}
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
finally{
System.out.println(5);
}
System.out.println(6);
}
}输出结果:
D:\Java\code\练习十二>java Test
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:6)throw与throws关键字
class User{
private int age;
public void setAge(int age) throws Exception{
if(age <= 0){
Exception e = new Exception("input age is error!");
throw e;
}
else{
this.age=age;
}
}
}class Test{
public static void main(String[] args){
User u = new User();
try{
u.setAge(-20);
}
catch(Exception e){
System.out.println(e);
}
}
}D:\Java\code\练习十二>java Test java.lang.Exception: input age is error!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。