java 中的try—catch异常处理
·
什么是try块
try块包含可能发生异常的代码块,try块通常要跟着一个catch块,这个catch块处理发生在try块中的异常。一个try块一定要跟着一个catch块或者是一个finally块,或者是两者都包含。
try块的语法:
try{
//可能包含异常的语句
}
什么是Catch块
一个catch块必须要和try块关联起来,在try块中发生异常后相应的catch块就要执行,例如在try块中发生异常,catch块中的异常处理语句就要执行。
java中try catch的语法:
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
try catch块的执行流程:
1、如果在try块中发生异常,那么执行控制就要从try块中传递到catch中去,这个异常就被相应的catch块抓住。一个try块可以和多个catch块关联起来,但是一个catch块只能处理一个异常类,程序同样也可以包含try-catch-finally块。
2、在执行完所有的这些块之后,finally块中的代码开始执行,程序并不强制要求包含finally块,但是如果你有finally块,不管有没有异常被try和catch块捕获或者抛出finally都会执行。
java中try catch的例子:
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
输出结果:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
在java中多个catch块:
1、一个try块可以有多个catch块
2、一个catch块是用来捕获class异常的同样可以捕获其他异常
语法:
catch(Exception e){
//This catch block catches all the exceptions
}
3、如果多个catch块在程序中出现,那么上边提到的catch块应该被放在最后,因为之前的每个处理都是最好的方式
4、如果try块没有抛出异常,那么catch块将会被完全忽略,程序照常运行
5、如果try块抛出异常,对应的catch块将会捕获它
6、所有的在捕获异常catch块中的语句将会被执行,然后程序继续运行
多个catch块的例子:
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
输出结果:
Warning: ArithmeticException
Out of try-catch block...
上边的例子是多个catch块的情况,当在try块中发生异常的时候这些catch块顺序的执行,这意味着如果你把最后一个catch块(catch(Exception e)f)放在第一个位置,就在try块之后,只要发生在try块中的异常那么这个catch块都可以捕获执行,这个try块应该放在最后来避免这样的情况
关注我,获取400个的赚钱金点子,轻松开启程序员的副业生涯

更多推荐
所有评论(0)