[
try-catch-finally的使用ExceptionTest1类
public class ExceptionTest1 {
@Test
public void test1(){
String str="123";
str="abc";
int num=0;
try {
//int num = Integer.parseInt(str);//抛出对象,不再执行下一行代码
num = Integer.parseInt(str);
System.out.println("hello---1");
}catch (NullPointerException e){//异常类型必须对应上,此时不会执行里面的代码
System.out.println("出现空指针异常,不要着急");
}catch (NumberFormatException e){//异常类型对应上了,会执行
//System.out.println("出现数值转换异常,不要着急");
//String getMessage();
//System.out.println(e.getMessage());//提示输入的是字符串abc不合适
//printStackTrace()
e.printStackTrace();
}catch (Exception e){//异常类型必须对应上,如果写别的异常还是报异常
System.out.println("出现异常,不要着急");
}
// System.out.println(num);num在try的结构中,调不了,可以把num声明在try外面然后在try里面赋值
System.out.println(num);
System.out.println("hello---2");
}
}
finally的使用
FinallyTest类
public class FinallyTest {
@Test
public void test2(){
try {
File file = new File("Hello.txt");
FileInputStream fis = new FileInputStream(file);
int data=fis.read();
while (data!=-1){
System.out.println((char)data);
data=fis.read();
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testMethod(){
int num=method();
System.out.println(num);
}
public int method(){
try {
int[] arr = new int[10];
System.out.println(arr[10]);
return 1;
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
return 2;
}finally {
System.out.println("我一定会被执行");
return 3;//三个return,return的是3
}
}
@Test
public void test1(){
try {
int a = 10;
int b = 0;
System.out.println(a / b);
}catch (ArithmeticException e){
// e.printStackTrace();
int[] arr = new int[10];
System.out.println(arr[10]);//算术异常后又出现了异常,正常应该要退出了
}catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("我好帅啊");
}
}
}



