package shilian.mylean.exception;
import org.testng.annotations.Test;
public class TestException {
/**
* IOException是编译期异常,这里编译时会报错
*/
@Test
public void test1() {
try{
start();
// }catch(IOException ioe){
} catch(Exception ioe) {
ioe.printStackTrace();
}
}
public static void start() {
System.out.println("Java Exception interivew question Answers for Programmers");
}
/**
* 第一个catch将异常处理过之后,下面将不会执行
*/
@Test
public void test4() {
try{
start1();
} catch(Exception ex) {
ex.printStackTrace();
}
/* catch (RuntimeException re) {
re.printStackTrace();
}*/
}
public static void start1() throws RuntimeException {
throw new RuntimeException("Not able to Start");
}
/**
* 程序返回1,程序先运行return,再运行finally语句
*/
@Test
public void test2() {
System.out.println(test());
}
static int test() {
int x = 1;
try{
return x;
} finally {
++x;
}
}
/**
* 程序打印2
*/
@Test
public void test3() {
System.out.println(get());
}
public static int get() {
try{
return 1;
} finally {
return 2;
}
}
/**
* finally中的代码比return语句后执行
*/
@Test
public void test6() {
System.out.println(new TestException().start6());
}
int start6() {
try{
return func1();
} finally {
return func2();
}
}
int func1() {
System.out.println("func1");
return 1;
}
int func2() {
System.out.println("func2");
return 2;
}
/**
* 如果执行finally代码块之前JVM退出了,finally块中的代码还会执行吗?
*/
@Test
public void test7() {
System.out.println(new TestException().start7());
}
static int start7() {
try{
System.out.println("try");
System.exit(0);
} finally {
return 1;
}
}
/**
* 空指针异常
*/
@Test
public void test8() {
System.out.println(start8(null));
}
static String start8(String name) {
if("shilian".equals(name)) {
return "hello world" + name;
}
return null;
}
}
java异常常见问题汇总
最新推荐文章于 2022-11-13 21:02:48 发布