Reputation: 59
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.
Upvotes: 3
Views: 462
Reputation: 73568
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.
Upvotes: 2
Reputation: 35874
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.
Upvotes: 2
Reputation: 2401
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/
Upvotes: 2