【技术】Java入门:e.printStackTrace()和System.out输出顺序混乱的问题

/**
 * Created by jodie on 17/5/16.
 */
class ExcTest{
    static void genException(){
        int nums[]=new int[4];
        System.out.println("Before exception is generated.");
        nums[7]=10;
        System.out.println("this won't be displayed");
    }
}

class UseThrowableMethods
{
    public static void main(String args[]){
        try {
            ExcTest.genException();
        }
        catch (ArrayIndexOutOfBoundsException exc){
            System.out.println("Standard message is:");
            System.out.println(exc);
            System.out.println("\nStack trace:");
            exc.printStackTrace();
        }
        System.out.println("After catch");
    }
}


输出的时候出现混乱的情况。我们正常使用 printStackTrace()的时候默认是输出到System.err中去的,而普通的输出都是放入System.out,这两者都是对上层封装的输出流,在默认情况下两者是指向Console的文本流。所以两者可能会出现同步问题。可把exc.PrintStackTrace改为
exc.printStackTrace(System.out);
在printStackTrace()的时候指定输出流为System.out,通过回避System.err来实现Console中文本流的顺序问题。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值