简体   繁体   中英

Is there an equivalent of Python exceptions in Java?

I'm new on Java, and I would like to know if Java has something like Python exception handling, where you don't have to specify the exception type. Something like:

try:
    f = open('text.tx', 'r')
except:
    #Note you don't have to specify the exception
    print "There's an error here"

I hope you can help me.

Every exception in Java is some sort of extension of java.lang.Exception . So you can always do:

try {
   // something that maybe fails
} catch (Exception e) { 
   // do something with the exception
}

It will catch any other type of exception, you just won't know what the actual exception is, without debugging.

Yes there is something called the try and catch block it looks something like this:

try
{
   //Code that may throw an exception
}catch(Exception e)
{
   //Code to be executed if the above exception is thrown
}

For your code above it could possibly be checked like this:

try
{
    File f = new File("New.txt");
} catch(FileNotFoundException ex)
{
    ex.printStackTrace();
}

Hope this helps look at this for more information: https://docs.oracle.com/javase/tutorial/essential/exceptions/

You can't leave out the exception type, but the widest try-catch block would be:

try {
    // Some code
} catch(Throwable t) {
    t.printStackTrace();
}

which catches Exceptions , Errors and any other classes implementing Throwable that you might want to throw.

It would also be incredibly foolish to use that anywhere, especially in something as simple as file access. IOException is a checked exception, so whenever you're doing file operations you'll be reminded by the compiler to handle that exception. There's no need to do a catch-all, it only makes your code more brittle.

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