您的位置:首页 > 编程语言 > Java开发

java异常常见问题汇总

2015-07-05 19:45 531 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: