Find all unchecked exceptions thrown by method?
Dear all,
I am writing critical code that must be correct. Thus, I wish to know that I have not overlooked any important unchecked exceptions. I am aware that the distinction between unchecked and checked exceptions is controversial, and I know the difference between these types of exceptions.
I would like to see for each function a list of all possible exceptions a method can throw. Preferably I would like a tool to do this for me, but I would write something myself if there is a reasonably simple way to do it.
More precisely, I would like to be able to define the set of "unchecked" exceptions myself, e.g., I would put down NullPointerException as "unchecked", but I would let IOException be checked (in my particular application, not in general). In general, this would however be a very nice language feature that could perhaps be a compromise in the (un)checked exceptions-controversy. Each programmer could define an "unchecked"-filter. Perhaps it would best be viewed as a kind of lint.
In any case, I have not found any tool, and it seems I can not do it myself with reflection, since it only gives access to declared exceptions, i.e., if the JDK-programmer decided not to put IOException in the signature of a method, then reflection can not see that the method may throw such an exception.
Does anybody know how to do this?
Douglas1024 wrote:
Thank you for your time, but I am well aware how one uses exceptions in normal code.
From an abstract point of view exceptions are simply a form of outputs from a method. Thus, if the goal is to write correct and easily verifiable code, in contrast to the vast majority of code that simply works reasonably, it is quite meaningful to know exactly what kinds of exceptions are thrown by a method and when.
Please note my correction regarding IOException.Millions upon millions of lines of correct code have been written following these standard java exception principles. The notion that you can write "better" code by detailing every single unchecked exception that could possibly be thrown is ludicrous. In fact by handling unchecked exceptions you will in all likelihood do more harm than good, hence why they are unchecked in the first place.
Similar Messages
-
i try run VS 2012 with /SafeMode. I create new empty Winform. When I start debug, I got:
"error while trying to run project uncaught exception thrown by method called through reflection"Hi Matanya Zac,
Did you restart your machine? How about installing the VS2012 update 4?
>>error while trying to run project uncaught exception thrown by method
Did you install the VS update in your VS IDE? I met this issue before which was related to the VS update:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5ead8ee9-ea09-4060-88b0-ee2e2044ff82/error-while-trying-to-run-a-project-uncaught-exception-thrown-by-method-called-through-reflection?forum=vsdebug
If still no help, I suggest you repair your VS, and then restart your machine, test the result.
Best Regards,
Jack
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Communcation Channel Type E-Mail Receiver Exception thrown in method proces
Hi,
I use a scenario R/3 IDOC -> XI -> Email. It is working, however the email is send 4 times.
I have an error within a communication channel.
Adaptertype E-Mail Direction Receiver
The communcation channel message log show the following entry:
2008-08-14 12:47:09 Erfolgreich Message wurde erfolgreich vom Messaging-System empfangen. Profil: XI URL: http://host:port/MessagingSystem/receive/AFW/XI Credential (User): PIISUSER
2008-08-14 12:47:09 Erfolgreich Mit der Verbindung Mail_http://sap.com/xi/XI/System. Versuch die Message in die Empfangs-Queue zu stellen
2008-08-14 12:47:09 Erfolgreich Message erfolgreich in Queue gestellt
2008-08-14 12:47:09 Erfolgreich Die Message wurde erfolgreich aus der Empfangs-Queue abgerufen
2008-08-14 12:47:09 Erfolgreich Der Status der Message wurde auf DLNG gesetzt
2008-08-14 12:47:09 Erfolgreich Liefert an Kanal: CC_Application_Mail_RCV
2008-08-14 12:47:09 Erfolgreich MP: Tritt in den Modulprozessor ein
2008-08-14 12:47:09 Erfolgreich MP: Lokales Modul localejbs/sap.com/com.sap.aii.adapter.mail.app/XIMailAdapterBean wird verarbeitet
2008-08-14 12:47:09 Erfolgreich Mail: message entering the adapter
2008-08-14 12:47:09 Erfolgreich Mail: Receiver adapter entered with qos ExactlyOnce
2008-08-14 12:47:09 Erfolgreich Mail: calling the adpter for processing
2008-08-14 12:47:09 Erfolgreich Mail: call completed
2008-08-14 12:47:09 Erfolgreich Mail: continuing to response message 58650010-69ee-11dd-bc24-0018fe76622e
2008-08-14 12:47:09 Erfolgreich Mail: sending a delivery ack ...
2008-08-14 12:47:09 Erfolgreich Mail: sent a delivery ack
2008-08-14 12:47:09 Erfolgreich MP: Lokales Modul localejbs/AF_Modules/MessageTransformBean wird verarbeitet
2008-08-14 12:47:09 Fehler MP: Ausnahme aufgetreten mit Grund com.sap.engine.services.ejb.exceptions.BaseTransactionRolledbackLocalException: Exception thrown in method process. The transaction is marked for rollback.
2008-08-14 12:47:09 Fehler Ausnahme aufgetreten beim Adapter-Framework: Exception thrown in method process. The transaction is marked for rollback.
2008-08-14 12:47:09 Fehler Zustellung der Message an die Anwendung über Mail_http://sap.com/xi/XI/System ist fehlgeschlagen weil: com.sap.aii.af.ra.ms.api.RecoverableException: Exception thrown in method process. The transaction is marked for rollback.: com.sap.engine.services.ejb.exceptions.BaseTransactionRolledbackLocalException: Exception thrown in method process. The transaction is marked for rollback.
2008-08-14 12:47:09 Erfolgreich Der Status der Message wurde auf WAIT gesetzt
2008-08-14 12:47:09 Erfolgreich Die Zustellung der asynchronen Message um Thu Aug 14 12:52:09 CEST 2008 wurde erfolgreich eingeplant.
Does anybody know what do to?
Best regards,
Nils KlothHi,
it seems that the module processing is not working, if the flag keep attachments is not checked.
Best regards,
Nils Kloth -
Is there anywhere in the docmentation where I can find a list of exceptions that may be thrown by a method in a standard Java API?
Thanks for any help you can give.
Pat Moranjava.lang
Class Exception
java.lang.Object
|
--java.lang.Throwable
|
--java.lang.Exception
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadLocationException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DestroyFailedException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvalidMidiDataException, InvalidPreferencesFormatException, InvocationTargetException, IOException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ServerNotActiveException, SQLException, TooManyListenersException, TransformerException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URISyntaxException, UserException, XAException -
Exceptions thrown by methods in classes
Hi all,
Just curios why the PrintWriter method close() is not declared as throwing IOException, although in JDK 5.0, PrintWriter implements Closable interface. And IOException is a checked exception.
Thank youRight.
No I remebered that the "implements" relationship allows for the set of checked exceptions to be narrowed in the throws clause. This is because when a client is using the interface it MUST catch all the checked exceptions, even if the implementation does not actually throw all of them.
This is true also when implementing abstract classes.
Thank you -
Find all redefined implementations of abstract method
Hi folks,
always the same: I have an interface defining methods with interface parameters. Then I have 1..n inherited classes. If I change the methods parameters in the interface, I have to apply changes to all implementations.
Also, having a methods name, I want to see all inherited implementations. Is there any way more convenient than poke manually through the object tree?
Regards,
ClemensYes, it is easy: Right-click in the class interface, choose inheritance relations (Shift-F9).
Too bad I can't reward points for the solution..
Regards,
Clemens -
Servlet losing connection to bean after a one Unchecked exception.
i get this exception continuously :
20010827175301793 ERROR 27 Aug 2001 17:53:01,793 CMServlet :
java.rmi.NoSuchObjectException: <mapped>
at java.lang.Throwable.fillInStackTrace(Native Method)
at java.lang.Throwable.fillInStackTrace(Compiled Code)
at java.lang.Throwable.<init>(Compiled Code)
at java.lang.Exception.<init>(Compiled Code)
at java.io.IOException.<init>(Compiled Code)
at java.rmi.RemoteException.<init>(RemoteException.java:56)
at java.rmi.NoSuchObjectException.<init>(NoSuchObjectException.java:50)
at com.kivasoft.eb.EBExceptionUtility.idToSystem(Unknown Source)
at com.kivasoft.ebfp.FPUtility.replyToException(Unknown Source)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_stub_WapCMEntrance.exec
ute(ejb_kcp_stub_WapCMEntrance.java:356)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_stub_WapCMEntrance.execute(
ejb_stub_WapCMEntrance.java:71)
at com.valis.cellmate.servlets.CMServlet.executeCmd(CMServlet.java)
at
com.valis.cellmate.servlets.LoginHandler.updateServerOnUserLogin(LoginHandle
r.java)
at
com.valis.cellmate.servlets.BackdoorLogger.doGetOrPost(BackdoorLogger.java)
at com.valis.cellmate.servlets.CMServlet.service(Compiled Code)
at javax.servlet.http.HttpServlet.service(Compiled Code)
at com.netscape.server.servlet.servletrunner.ServletInfo.service(Compiled
Code)
at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Compiled
Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Compiled Code)
at java.lang.Thread.run(Compiled Code)
After i get once an unchecked exception :
20010827175231868 ERROR 27 Aug 2001 17:52:31,869 CMServlet :
com.netscape.server.eb.UncheckedException: unchecked exception thrown by
impl [email protected]513cb;
nested exception is:
java.lang.NullPointerException
java.lang.NullPointerException
at
com.valis.cellmate.wap.statelessSessionBeans.WapCMEntranceBean.execute(WapCM
EntranceBean.java)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_skel_com_valis_cellmate_wap
statelessSessionBeansWapCMEntranceBean.execute(ejb_skel_com_valis_cellmate
wapstatelessSessionBeans_WapCMEntranceBean.java:65)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_skel_WapCMEntrance.exec
ute__com_valis_util_ACmdResults__com_valis_util_LogicalCmdParams__127782180(
ejb_kcp_skel_WapCMEntrance.java:219)
at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
at com.kivasoft.ebfp.FPRequest.invoke(Unknown Source)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_stub_WapCMEntrance.exec
ute(ejb_kcp_stub_WapCMEntrance.java:328)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_stub_WapCMEntrance.execute(
ejb_stub_WapCMEntrance.java:71)
at com.valis.cellmate.servlets.CMServlet.executeCmd(CMServlet.java)
at
com.valis.cellmate.servlets.FindIMateHandler.doGetOrPost(FindIMateHandler.ja
va)
at com.valis.cellmate.servlets.CMServlet.service(Compiled Code)
at javax.servlet.http.HttpServlet.service(Compiled Code)
at com.netscape.server.servlet.servletrunner.ServletInfo.service(Compiled
Code)
at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Compiled
Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Compiled Code)
at java.lang.Thread.run(Compiled Code)
Hed Bar-Nissan
Valis R&Di get this exception continuously :
20010827175301793 ERROR 27 Aug 2001 17:53:01,793 CMServlet :
java.rmi.NoSuchObjectException: <mapped>
at java.lang.Throwable.fillInStackTrace(Native Method)
at java.lang.Throwable.fillInStackTrace(Compiled Code)
at java.lang.Throwable.<init>(Compiled Code)
at java.lang.Exception.<init>(Compiled Code)
at java.io.IOException.<init>(Compiled Code)
at java.rmi.RemoteException.<init>(RemoteException.java:56)
at java.rmi.NoSuchObjectException.<init>(NoSuchObjectException.java:50)
at com.kivasoft.eb.EBExceptionUtility.idToSystem(Unknown Source)
at com.kivasoft.ebfp.FPUtility.replyToException(Unknown Source)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_stub_WapCMEntrance.exec
ute(ejb_kcp_stub_WapCMEntrance.java:356)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_stub_WapCMEntrance.execute(
ejb_stub_WapCMEntrance.java:71)
at com.valis.cellmate.servlets.CMServlet.executeCmd(CMServlet.java)
at
com.valis.cellmate.servlets.LoginHandler.updateServerOnUserLogin(LoginHandle
r.java)
at
com.valis.cellmate.servlets.BackdoorLogger.doGetOrPost(BackdoorLogger.java)
at com.valis.cellmate.servlets.CMServlet.service(Compiled Code)
at javax.servlet.http.HttpServlet.service(Compiled Code)
at com.netscape.server.servlet.servletrunner.ServletInfo.service(Compiled
Code)
at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Compiled
Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Compiled Code)
at java.lang.Thread.run(Compiled Code)
After i get once an unchecked exception :
20010827175231868 ERROR 27 Aug 2001 17:52:31,869 CMServlet :
com.netscape.server.eb.UncheckedException: unchecked exception thrown by
impl [email protected]513cb;
nested exception is:
java.lang.NullPointerException
java.lang.NullPointerException
at
com.valis.cellmate.wap.statelessSessionBeans.WapCMEntranceBean.execute(WapCM
EntranceBean.java)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_skel_com_valis_cellmate_wap
statelessSessionBeansWapCMEntranceBean.execute(ejb_skel_com_valis_cellmate
wapstatelessSessionBeans_WapCMEntranceBean.java:65)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_skel_WapCMEntrance.exec
ute__com_valis_util_ACmdResults__com_valis_util_LogicalCmdParams__127782180(
ejb_kcp_skel_WapCMEntrance.java:219)
at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
at com.kivasoft.ebfp.FPRequest.invoke(Unknown Source)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_kcp_stub_WapCMEntrance.exec
ute(ejb_kcp_stub_WapCMEntrance.java:328)
at
com.valis.cellmate.wap.statelessSessionBeans.ejb_stub_WapCMEntrance.execute(
ejb_stub_WapCMEntrance.java:71)
at com.valis.cellmate.servlets.CMServlet.executeCmd(CMServlet.java)
at
com.valis.cellmate.servlets.FindIMateHandler.doGetOrPost(FindIMateHandler.ja
va)
at com.valis.cellmate.servlets.CMServlet.service(Compiled Code)
at javax.servlet.http.HttpServlet.service(Compiled Code)
at com.netscape.server.servlet.servletrunner.ServletInfo.service(Compiled
Code)
at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Compiled
Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.applogic.AppLogic.execute(Compiled Code)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Native Method)
at com.kivasoft.thread.ThreadBasic.run(Compiled Code)
at java.lang.Thread.run(Compiled Code)
Hed Bar-Nissan
Valis R&D -
From a book:
"When a class undergoes revision, it is not a violation of source or binary compatibility if an exported method is modified to throw additional unchecked exceptions.
Suppose a class invokes a method from another, independently written class. The authors of the former class may carefully document all of the unchecked exceptions that each method throws, but if the latter class is revised to throw additional unchecked exceptions, it is quite likely that the former class (which has not undergone revision) will propagate the new unchecked exceptions even though it does not declare them."
What does the last line about propagating mean? It sounded pretty simple up until then...what I got was that your code can call other code that can add unchecked exceptions at any time...correct? I just don't understand the ending.
Thanks.But I thought one main differentiating factor of
unchecked exceptions is (more often than not -- if
not always) that you cannot recover from them.You generally either can't or shouldn't, because they're a sign of a programming error or of seros system trouble.
I'd think it'd be an irrelevant point that a callee
could add new unchecked exceptions because (forget
the new unchecked exceptions)It's worth making it clear that unchecked exceptions are not part of the method's contract.
what's a coder to do
with unchecked exceptions the callee already HAS
documented!?Usually nothing. Often it's just worth documenting them as a way laying out preconditions, assumptions, and limitations of the method being called. -
What are all the exceptions thrown by JDBC ?
I think the Exceptions are :
BatchUpdateException
DataTruncation
SQLException
SQLWarning
See Java Documentation for more details -
How to find the parameters names of a method using reflection?
Hi,
Using the function getParameterTypes(), it is possible to find all parameter types from a Method. However, is there a way to find all parameters NAMES of a Method?
If the asnwer is no, is there an easy way to obtain this information using the java source code (I mean, that doesn't need to create a parser)?
ThanksThe same way. Primitive types, even though they do not extend java.lang.Object, and are not objects, still have an associated Class object
-
Wehre can i find all the throw and catch exceptions
I havent had much success figuring out which predefined exceptions i should/can use. Can someone please guide me where i can find out what kind of throw and catch exceptions are there in java and how and where can i find them. thanks.
Read this first: http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44044
You can't find them all anywhere. You'll just encounter them as you use different APIs.
One of the most basic concepts around exceptions has to do with the difference between checked and unchecked exceptions. Any exception that extends RuntimeException is unchecked. Which means that if you call a method that throws an unchecked exception, you don't have to provide a catch block. These exceptions are usually thrown for things that could be avoided, i.e. programmer error.
The compiler will require you to have a catch block for all checked exceptions. This means you should take steps in your code to handle them and retry the operation, such as user errors. -
Differentiating between same exception thrown from 2 different methods
Suppose I have a class CodeDAO which has 2 methods who both throw SQLException
public int getLocationCode(String locationName) throws SQLException;
public int getDepartmentCode(String departmentName) throws SQLException;Now I have a business method in which I have to use both of the above DAO methods.
public int process() {
try {
CodeDAO codeDAO = new CodeDAO();
int locationCode = codeDAO.getLocationCode("NJ");
int departmentCode = codeDAO.getDepartmentCode("Sales");
catch (SQLException e) {
}If SQLException is thrown how will I know if it is thrown by the getLocationCode method or getDepartmentCode method?
What are the different choices I have in differentiating between same exception thrown from different methods? And which choice do you guys prefer?
Thankssrhcan wrote:
maheshguruswamy wrote:
srhcan wrote:
gimbal2 wrote:
baftos wrote:
Put each method invokation in its own try/catch block.Or in fact not use SQLException, but exceptions that are unique.So each DAO method has its own exception?
public int getLocationCode(String locationName) throws GetLocationCodeException;
public int getDepartmentCode(String departmentName) throws GetDepartmentCodeException;would not that means I have to create a lot of exception classes?
Edited by: srhcan on Aug 9, 2012 2:54 PMLet me ask you this, what do you plan to do in the catch block? Do some sort of recovery? rollback? If it is just for logging purposes, I am pretty sure the exception message will give you enough information to find out where the error was.* I would like to give user a specific message based on which method fails. So if getLocationCode("NJ") fails the message can be: Unable to find code for Location "NJ". And if getDepartmentCode("Sales") fails the message can be: Unable to find code for Department "Sales".
* I would like to print the exception's stacktrace in the log file.
* I may do a rollback depending on if its an INSERT/UPDATE/DELETE statement.Well, in that case why not log it in the DAO methods themselves...inside getLocationCode and getDepartmentCode. Instead of trying to do the recovery/logging in the process method, do it in the individual dao methods. The calling classes should not be responsible for logging/recovery etc. It should be done in the DAO classes themselves and the DAO method should return an appropriate message/code to the consumer tier classes indicating the status of the transaction. Just my 0.02$. -
How to handle exception thrown in standard bo method in the workflow design
Hi Experts
how to handle exception thrown from standard bo method in the workflow design. For example, bo BUS2032, METHOD confirm. If the user cancel it, it will throw exception. In the workflow, how to catch this exception and add corresponding steps in the workflow.@jrockman li
Try to implement the logic that what ever you are performing in the BO mehtod in a FM and in the FM you have tab with name EXECPTIONS define the execption in that tab.Now in the BO method you call this FM and if the exception occurs by using RAISE you can raise the exception in the FM and based on the number of exceptions your sy-subrc value will be set
so when sys-subrc is not eq 0 then pass a value back t the workflow container., I think this will work.
a sample Snippet for understanding purpose
CALL FUNCTION 'GUI_DOWNLOAD'
EXPORTING
filename = <path>
filetype = 'ASC'
IMPORTING
filelength = lv_len
TABLES
data_tab = l_txt_tab
EXCEPTIONS
file_write_error = 1 " If this Exception occurs
invalid_type = 2
no_authority = 3
unknown_error = 4
OTHERS = 10.
CASE sy-subrc.
WHEN 1. " SY-SUBRC value will be 1 then,
" Pass or set the value back to the workflow conatiner element
ENDCASE. -
How to find all the methods in oops
Hi all,
is there any way to find all the methods of all class in a single screen j(ust like using t.code se37 we can find all the fm created)
sathishHi,
1.Go to the class builder(SE24).
2.Type the class name[eg..cl_gui_alv_grid]
3.You will see a tab called methods.Click that.In that,you can view all the methods.Place the cursor in a method and click parameter tab.You can find the parameters for the method.
Kindly reward points by clicking the star on the left of reply,if it helps. -
Changing exception clause in method signature when overwriting a method
Hi,
I stumbled upon a situation by accident and am not really clear on the details surrounding it. A short description:
Say there is some API with interfaces Foo and Bar as follows:
public interface Foo {
void test() throws Exception;
public interface Bar extends Foo {
void test();
}Now, I find it strange that method test() for interface Bar does not need to define Exception in its throws clause. When I first started with Java I was using Java 1.4.2; I now use Java 1.6. I cannot remember ever reading about this before and I have been unable to find an explanation or tutorial on how (or why) this works.
Consider a more practical example:
Say there is an API that uses RMI and defines interfaces as follwows:
public interface RemoteHelper extends Remote {
public Object select(int uid) throws RemoteException;
public interface LocalHelper extends RemoteHelper {
public Object select(int uid);
}As per the RMI spec every method defined in a Remote interface must define RemoteException in its throws clause. The LocalHelper cannot be exported remotely (this will fail at runtime due to select() in LocalHelper not having RemoteException in its clause if I remember correctly).
However, an implementing class for LocalHelper could represent a wrapper class for RemoteHelper, like this:
public class Helper implements LocalHelper {
private final RemoteHelper helper;
public Helper(RemoteHelper helper) {
this.helper = helper;
public Object select(int id) {
try {
return (this.helper.select(id));
} catch(RemoteException e) {
// invoke app failure mechanism
}This can uncouple an app from RMI dependancy. In more practical words: consider a webapp that contains two Servlets: a "startup" servlet and an "invocation" servlet. The startup servlet does nothing (always returns Method Not Allowed, default behaviour of HttpServlet), except locate an RMI Registry upon startup and look up some object bound to it. It can then make this object accessible to other classes through whatever means (i.e. a singleton Engine class).
The invocation servlet does nothing upon startup, but simply calls some method on the previously acquired remote object. However, the invocation servlet does not need to know that the object is remote. Therefore, if the startup servlet wraps the remote object in another object (using the idea described before) then the invocation servlet is effectively removed from the RMI dependancy. The wrapper class can invoke some sort of failure mechanism upon the singleton engine (i.e. removing the remote object from memory) and optionally throw some other (optionally checked) exception (i.e. IllegalStateException) to the invocation servlet.
In this way, the invocation servlet is not bound to RMI, there can be a single point where RemoteExceptions are handled and an unchecked exception (i.e. IllegalStateException) can be handled by the Servlet API through an exception error page, displaying a "Service Unavailable" message.
Sorry for all this extensive text; I just typed out some thoughts. In short, my question is how and why can the throws clause change when overwriting a method? It's nothing I need though, except for the clarity (e.g. is this a bad practice to do?) and was more of an observation than a question.
PS: Unless I'm mistaken, this is basically called the "Adapter" or "Bridge" (not sure which one it is) pattern (or a close adaptation to it) right (where one class is written to provide access to another class where the method signature is different)?
Thanks for reading,
YuthuraYuthura wrote:
I know it may throw any checked exception, but I'm pretty certain that an interface that extends java.rmi.Remote must include at least java.rmi.RemoteException in its throws clause (unless the spec has changed in Java 1.5/1.6).No.
A method can always throw fewer exceptions than the one it's overriding. RMI has nothing to do with it.
See Deitel & Deilte Advanced Java 2 Platform How To Program, 1st Ed. (ISBN 0-13-089650-1), page 793 (sorry, I couldn't find the RMI spec quick enough). Quote: "Each method in a Remote interface must have a throws clause that indicates that the method can throw RemoteException".Which means that there's always a possibility of RemoteException being thrown. That's a different issue. It's not becusae the parent class can throw RE. Rather, it's because some step that will always be followed is declared to throw RE.
I later also noticed I could not add other checked exceptions, which made sense indeed. Your explanation made perfect sense now that I heard (read) it. But just to humour my curousity, has this always been possible? Yes, Java has always worked that way.
PS: The overwriting/-riding was a grammatical typo (English is not my native language), but I meant to say what you said.No problem. Minor detail. It's a common mistake, but I always try to encourage proper terminology.
Maybe you are looking for
-
How to use a table to fill an array
I have a cFP 2110 with a couple of relay modules I'm using to automate a process. I'm using an array of a cluster of elements to turn the relays on and off with a time delay for each step. This was the first version I started with and I have since
-
Af:commandButton only works for the first 10 rows returned in the af:table
Using JDeveloper 10.1.3.2.0. I am new to ADF programming. I have attempted to create an ADF page that contains a search and return table in the same page. The search appears to work fine but the return table displays odd behavior. If the search retur
-
Why do I have 2 iPhoto Library icons?
Hello I have 2 unrelated issues. (I believe) First, In my home folder...picutures folder, I have 2 iPhoto Library icons. one with a date modified 20/6/2010 size 45.98GB. the other date modified Today 44.65 GB. In the last few days I have been deletin
-
Trotz neuestem Java update für OS X 10.6.8 erhalte ich die Meldung : fehlendes Plug-In. Was kann ich tun?
-
SMS starting with Status:
Nokia Suite and Nokia PC Suite won't show SMS correctly if line begins with Status: I have a gadget that is controlled via SMS and the status messages I get from the gadget are not fully visible in Nokia Suite nor PC Suite. Any hints how to override