• Java如何打印异常的堆栈?


    在Java编程中,如何打印异常的堆栈?

    此示例显示如何使用异常类的printStack()方法打印异常的堆栈。

    package com.yiibai;
    
    public class PrintStackTrace {
        public static void main(String args[]) {
            int array[] = { 20, 20, 40 };
            int num1 = 15, num2 = 10;
            int result = 10;
            try {
                result = num1 / num2;
                System.out.println("The result is" + result);
    
                for (int i = 5; i >= 0; i--) {
                    System.out.println("The value of array is" + array[i]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    The result is1
    java.lang.ArrayIndexOutOfBoundsException: 5
        at com.yiibai.PrintStackTrace.main(PrintStackTrace.java:13)
    
    Shell

    示例-2

    以下是Java中打印异常堆栈的另一个例子。

    package com.yiibai;
    
    public class PrintStackTrace2 {
        public static void main(String[] args) {
            try {
                ExceptionFunc();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    
        public static void ExceptionFunc() throws Throwable {
            Throwable t = new Throwable("This is new Exception in Java...");
    
            StackTraceElement[] trace = new StackTraceElement[] {
                    new StackTraceElement("ClassName", "methodName", "fileName", 5) };
            t.setStackTrace(trace);
            throw t;
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    java.lang.Throwable: This is new Exception in Java...
        at ClassName.methodName(fileName:5)
  • 相关阅读:
    随笔
    随笔
    随笔1
    随笔2
    intellij-maven-imports-have-broken-classpath
    如何使用idea把web项目打成war包
    spring-wind 搭建过程问题记录
    windows 64位 安装mvn提示 不是内部或外部命令
    面试碰到“为何从上家离职”...
    nginx 两台机器 出现退款失败问题
  • 原文地址:https://www.cnblogs.com/borter/p/9613546.html
Copyright © 2020-2023  润新知