This website requires JavaScript.

Java 异常处理和调试

Try/Catch

TryCatch

public class Main {

public static void main(String[] args) {
    try {
        String[] strings = {"Welcome!"};
        System.out.println(strings[1]);
    } catch (Exception e) {

// e.printStackTrace(); System.out.println("There was an error"); } System.out.println("The application is still running!"); } }

 Throws

public class Main {

    public static void main(String[] args) {
        try {
            getArrayItem();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array item was out of bounds");
        }
    }

    private static void getArrayItem()
    throws ArrayIndexOutOfBoundsException{
        String[] strings = {"Welcome!"};
        System.out.println(strings[1]);
    }

}

命令行调试

样例代码:

public class DebugDemo { public static void main(String[] args) { String message = args[0]; System.out.println(message); } }
编译程序:

javac DebugDemo.java -g
初始化jdb:
jdb DebugDemo "Welcome to BiHell.com" -Xdebug -Xrunjdwp:transport=st_socket,server=y,address=8000,suspendy=y
在DebugDemo类第五行暂停
stop at DebugDemo:5
输入run 开始运行程序
run
如图所示,断电在第五行 System.out.println(message);

java-debug-run

打list 可以显示我们所有的代码:

java-debug-list

此时我们可以打印出我们接受的变量,如:

print args[0] print message cont

![java-debug-value](http://www.bihell.com/wp-content/uploads/2015/06/java-debug-value.png)
0条评论
avatar