这篇文章主要为大家展示了如何使用Java异常处理,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
成都创新互联专注为客户提供全方位的互联网综合服务,包含不限于做网站、成都网站制作、南宫网络推广、小程序设计、南宫网络营销、南宫企业策划、南宫品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;成都创新互联为所有大学生创业者提供南宫建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com
异常:

算术异常类:ArithmeticExecption
空指针异常类:NullPointerException
类型强制转换异常:ClassCastException
数组下标越界异常:ArrayIndexOutOfBoundsException
输入输出异常:IOException



public class Demo {
public static void main(String[] args) {
// int a=10/0;
try{
int a=10/0;
}catch(ArithmeticException e) {
System.out.println("run in ArithmeticException "+e);
//run in ArithmeticException java.lang.ArithmeticException: / by zero
}
catch (Exception e) {
System.out.println(e);
}finally {
System.out.println("最终执行的");//最终执行的
}
}
}throws用于声明异常,声明函数可能发生的异常。【当函数中有throw来抛出异常时,函数头必须使用throws声明异常】
throw用于手动抛出异常,可以抛出自定义异常信息:throw 异常类型(异常信息)
public class Demo2 {
static int div(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException("发生除零异常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(ArithmeticException e) {
System.out.println(e.getMessage());//发生除零异常了!
}finally {
System.out.println("in finally");//in finally
}
System.out.println("after finally");//after finally
}
}一般对于不想在函数中处理异常时,一般采用异常抛出处理(throw throws);否则使用try…catch…finally捕获异常。
有时候没有定义我们想要的异常(比如我们MySQL连接异常),那么我们可以自定义异常。
class MyException extends Exception{
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Demo3 {
static int div(int a,int b) throws MyException {
if (b==0){
throw new MyException("发生异常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(Exception e) {
System.out.println(e);//异常.MyException: 发生除零异常了!
}
}
}
public class Demo {
public static void main(String[] args) {
Boolean food=false;
System.out.println("准备开始吃饭");
assert food;
System.out.println("饭来了");
}
}
以上就是关于如何使用Java异常处理的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。