简体   繁体   English

JAVA中的异常处理

[英]Handling exceptions in JAVA

I know that if we have a normal code without try and catch statements,then if an exception occurs,then the default exception handler of JVM handles that exception.我知道如果我们有一个没有 try 和 catch 语句的普通代码,那么如果发生异常,则 JVM 的默认异常处理程序会处理该异常。 I have a code...我有一个代码...

public class St
{
    public static void main(String args[])
    {
        try
        {
            int y=23/0;
        }
        catch(Exception e)
        {
            System.out.println("Division by zero");
        }
    }
}

As far as I know, in this code exception occurs at line 7,an object of class Exception is thrown and that's why we have taken as argument an object of class Exception in order to catch the exception.Am I right upto now????据我所知,在这段代码中,异常发生在第 7 行,抛出了一个 Exception 类的对象,这就是为什么我们将 Exception 类的对象作为参数以捕获异常。我现在到了吗??? ?

But why this code shows a compile time error...但是为什么这段代码显示编译时错误......

public class St
{
    public static void main(String args[])
    {
        Exception e=new Exception();
        try
        {
            int y=23/0;
        }
        catch(e)
        {
            System.out.println("Division by zero");
        }
    }
}

In this I have created an object reference e of class Exception,and that I have taken as argument in catch.But its not running,giving error at compile time.Can someone explain why???在此,我创建了一个类 Exception 的对象引用 e,并且我在 catch 中将其作为参数。但它没有运行,在编译时出错。有人可以解释为什么吗???

That's just not how the catch block works.这不是 catch 块的工作方式。 It requires an ExceptionType argument and then a name to reference the exception once it's been caught.它需要一个 ExceptionType 参数,然后是一个名称来在它被捕获后引用异常。 It doesn't take an object as an argument, but the name of a class that inherits from 'Throwable'.它不接受一个对象作为参数,而是一个继承自“Throwable”的类的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM