简体   繁体   中英

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. 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????

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???

That's just not how the catch block works. It requires an ExceptionType argument and then a name to reference the exception once it's been caught. It doesn't take an object as an argument, but the name of a class that inherits from 'Throwable'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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