0

I have a java method which is potent of throwing multiple unchecked exceptions. My question is: do I need to declare it to throw all the the exceptions or Is there any problem if I declare throws Exception only?

Method 1:

public void myMethod() throws Exception1,Exception2,Exception3,Exception4,Exception5
{}

Instead of method 1, can I declare like this?

public void myMethod() throws Exception
{}
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
Praveen
  • 201
  • 5
  • 18
  • 3
    If your method throws only `unchecked exceptions`, you don't need any throws clause. – Eran Nov 12 '14 at 09:35

4 Answers4

1

Yes you can, but ideally people choose a specific type of Exception so that you know which type of "Exceptional" behaviour that block of code is having. Exception is superclass - where other ones are subclasses. If you have unchecked exceptions, i.e. your code does behaviour that can be classified within "Unchecked" Exceptional behaviour, you can use Exceptions class. but otherwise you need Checkedones you mentioned above (may be not all of them).

If you don't understand what different type of exceptions do - try and read this - https://docs.oracle.com/javase/tutorial/essential/exceptions/

This will explain different exceptions and how to use them in your application :)

P.S. For unchecked exceptions, it is NOT required to use throws in your method signature - but using it possibly don't do any harm - at least you are letting people know that you have "An" exception that may be thrown by this code :) [ I am happy to be criticised for that]

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
1

Yes, you can define. But, method caller will loose some information about the exception thrown. Best practise is to throw specific exception and handle them specifically.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • 1
    +1, While catching also the same principle applies. Never catch a direct `Exception` which is super of all Exceptions. Always catch specific subclass Exception. – Suresh Atta Nov 12 '14 at 09:41
0

You can alway throw the root-exception. If your Exception1,Exception2,,Exception3,Exception4,Exception5 all extend the same exception somewhere in their heritage-tree you can throw this base-exception.

Be aware that exceptions could have a meaning, i.e. show what can go wrong (and give a hint to handle it). Thats especially important if some other developer has to deal with your method.

Ishkafel
  • 333
  • 1
  • 10
0

If the exceptions are from another functional area or not in your control, I would handle them (by logging, rollback, cleanup of resources, etc.) and wrap them in my own (Java: checked vs unchecked exception explanation) and throw that.

Community
  • 1
  • 1
wdk
  • 373
  • 2
  • 8