这篇文章主要为大家展示了如何使用Java异常处理,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
异常:
算术异常类: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异常处理的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。