3

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.

3
  • 2
    Maybe you're thinking of Java exceptions: docs.oracle.com/javase/tutorial/essential/exceptions Commented Aug 10, 2017 at 18:26
  • May be you should have a look at this Commented Aug 10, 2017 at 18:29
  • 1
    This is bad practice in Python. You definitely shouldn't do it there. I guess the equivalent in Java is catch (Exception e), although, probably that is equivalent to python except Exception as e: Commented Aug 10, 2017 at 18:30

3 Answers 3

2

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.