Catching exception of a super constructor
Is it possible to catch the exception thrown by a super class
constructor in a sub clas constructor?
public class A
public A() throws Exception
throw new Exception("Exception from A");
class B extends A
public B()
try
super();
catch(Exception e)
}I get an error saying,
A.java:16: call to super must be first statement in constructor
super();
^
Any thoughts?
More on this here,
http://archive.devx.com/free/tips/tipview.asp?content_i
=2384&Java=ONThanks for that link. I completely agree to what it says.
In other words, not being able to successfully construct our super class implies that we cannot create our derived class.
But I feel this must be mentioned clearly somewhere in JLS. And the error message that we get must be "You cannot catch exceptions thrown by a super class constructor".
Similar Messages
-
Catch exceptions that occur in the constructor of a managed bean
Hello,
I would like to catch exceptions that might occur in the constructor of a managed bean and redirect to an error page. My beans need to get data from a database and if the database is not accessible, an error page is to tell the user "try again later". I don't want to write an action or actionListener that is invoked by a button klick on the previous page to make error handling easier, because an actionListener should not know about the next page and what data the next page will need.
I read all postings about this topic I could find in this forum. And there are three solutions I tried:
1) register an error-page in web.xml
Is there an example for using this in a JSF application? It did not work. I got a "Page not found" exception
2) Use a phase listener. But how can a phase listener do this? Is there an example? I don't think it can do it in the beforePhase method because this method is called before the constructor of the managed bean is called.
3) Use a custom ViewHandler. This is my renderView method which creates a "Page not found" Exception.
public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException {
ViewHandler outer = context.getApplication().getViewHandler();
try {
super.renderView(context, viewToRender);
} catch (Exception e) {
context.getExternalContext().redirect("/error.jspx");
Several people write they've done it one or the other way. Please share your knowledge with us !!
Regards,
MareikeHallo Mareike,
Maybe I should abandon managed beans, create my own
"unmanaged" ones inside of an action listener and put
them somewhere my pages can find them.
Its a pity, because I like the concept of managed
beans.sure setter injection of JSF is fine!
well workaround could be using <h:dataTable rendered="#bean.dbAccessible" ...>
In your constructor you catch the exception and set
dbAccessible = false;
or you use error pages of webcontainer,
but the pages couldn't contain JSF components, IMHO
only plain JSP files.
BTW perhaps somebody on MyFaces' list knows the solution:
http://incubator.apache.org/myfaces/community/mailinglists.html
Regards,
Mareike-Matthias -
Catching exception from inherited constructor
Hi all,
If I'm extending a class and the constructor of the parent class throws an exception, is there any way to catch that exception in my constructor? What I would like to do is something like this.
public class MyClass extends OtherClass { // the constructor for OtherClass throws an exception
public MyClass() {
try {
super();
} catch (Exception e) {}
}But of course you can't do that because super() has to be the first command in the method. Is there any other way to accomplish this? My objective is to chain this exception to a different type of exception.Write a factory method? For example:
class ABCException extends Exception {}
class XYZException extends Exception {}
class OtherClass {
public OtherClass() throws ABCException {
throw new ABCException();
class MyClass extends OtherClass { // the constructor for OtherClass throws an exception
protected MyClass() throws ABCException {
super();
public static MyClass instance() throws XYZException {
try {
return new MyClass();
} catch (ABCException e) {
throw new XYZException();
} -
Exceptions thrown in Thread Constructors
Hi,
Im having a problem with exceptions been thrown during thread constructors... mainly that when it happens, the JVM still seems to track the dud thread as an active thread (See example code below).
As you can see, the thread throws an exception during creation, and hence never gets created as such (mt stays null). Yet Thread.activeCount() reports that its still hanging around somewhere, yet it cant be referenced. Unfortunately this is resulting in me getting a rather large buildup of these duds, as its part of a "retry" phase in my software.
Any thoughts/comments/suggestions?
Thanks,
Roger.
import java.net.Socket;
public class myMain
public myMain()
myThread mt=null;
while (true) try
System.out.println(Thread.activeCount());
Thread.sleep(100);
mt = new myThread();
catch (Exception ex)
System.out.println(mt);
System.err.println(ex);
public static void main (String[] args)
new myMain();
public class myThread extends Thread
public myThread() throws Exception
throw new Exception();
}It's not hard to obtain this reference (for instance we can catch exception in the constructor and do something before rethrowing it) - but what can we do with this reference? There's no way to destroy the thread object save starting it. But this is really ugly (but works):
public class NewThreadException {
public static class myThread extends Thread {
protected boolean stillborn;
public myThread() throws Exception
super(new ThreadGroup("My Group"), "My Thread");
try {
throw new Exception();
} catch (Exception e) {
stillborn=true;
start();
throw e;
public void run() {
if (stillborn) return;
public static void main(String[] args) {
myThread mt=null;
while (true) try
System.out.println(Thread.activeCount());
Thread.sleep(100);
mt = new myThread();
catch (Exception ex)
System.out.println(mt);
System.err.println(ex);
}BTW there's already one private stillborn in Thread class itself. -
Maybe a stupid question but is there any common practice when it comes to handling exceptions in Java? Should I declare throws for the whole method or should I use a try-catch construction? I can see the advantage of passing exception to the calling methods but this means that many methods must be throwables or catch the exceptions so it's kind of a circle of exceptions...
/PYou usually don't want to do
catch (Exception e) {}
Somewhat less onerous is
catch (Exception e) { //handle it }
Normally what you'd do is define your own exception classes that extend Exception. A common approach is to use a package-based hierarchy, with specific exceptions for specific types of errors.
// package com.mycompany.dbstuff might have these
public class DatabaseException extends Exception { /*...*/}
public class NoSuchTableException extends DatabaseException { /*...*/ }
public class LoginFailedException extends DatabaseException { /*...*/}
// package com.mycompany.accountmanagement package may have these
public class AccountException extends Exception {/*...*/}
public class IllegalAccountNumberExceptoin extends AccountException {/*...*/}
// etc.Each exception simply has constructors that call super(same args), and possibly the ability to take another Throwable as a constructor arg, which is then mapped to a member variable so you can later call getCause() or getWrappedException to see which exception led to this one.
At any given layer, you catch exception thrown by the layers it uses, and wrap them in an exception for your current layer.
// in the AccountClass
public AccountInfo getAccountInfo(int acctId) throws AccountException {
if (acctId < 0) {
throw new IllegalAccountNumberException("No negative account numbers");
try {
database.login(uname, passwd);
databse.getAccountInfo(acctId);
catch (DatabaseException exc) {
exc.printStackTrace();
throw new AccountException(exc);
}This way, the user of the accountmanagement package doesn't need to know what database package accountmanagement uses. If I call an accountmanagement method, I only have to deal with an account relatd exception. If it's IllegalAccountNumber, I can prompt the user to reenter the acct number. If it's other, I can say "Couldn't retrieve account info, please try again" or some such thing.
And yes, I know, if the login failed, you'd want to propagate that, so the user could reenter the password. I'd make a separate AccountLoginFailedException and wrap that around the DBLoginFailed, because the user of the Account class is trying to access the account, not the database.
Also, you often do want to print stack traces. Not in your user's face--off in a log file somehwere. If you've got exceptions that are ocurring for reasons other than user typos, you want to record as much info as you can about them. -
How to catch exception when have max connection pool
hi,
i have define in oracle user that i could have max 10 sessions at the same time.
I have jdbc datasource & connection pool defined at glassfish server(JSF application).
now, if in application is too many queries to the database then i have error: nullpointer exception - becouse when i try to do:
con = Database.createConnection(); - it generates nullpointer exception becouse there isn't free connection pool
i try to catch exception like this:
public List getrep_dws_wnioski_wstrzymane_graph() { int i = 0; try { con = Database.createConnection(); ps = (Statement) con.createStatement(); rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow"); while(rs.next()){ rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4))); i++; } } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new NoConnectionException(); // catch null 1 } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new NoConnectionException(); // catch null 2 } } return rep_dws_wnioski_wstrzymane_graph; }
but at line:
con.close();
i have nullpointerexception
and
at line
throw new NoConnectionException(); // catch null 2
i have: caused by exception.NoConnectionException
what's wrong with my exception class? how to resolve it?
public class NoConnectionException extends RuntimeException{ public NoConnectionException(String msg, Throwable cause){ super(msg, cause); } public NoConnectionException(){ super(); } }
at web.xml i have defined:
<error-page> <exception-type>exception.NoConnectionException</exception-type> <location>/NoConnectionExceptionPage.jsp</location> </error-page>thanks,
i did it and i have error:
java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: ORA-02391: exceeded simultaneous SESSIONS_PER_USER limit
at com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:115)
at logic.Database.createConnection(Database.java:37): conn = ds.getConnection();
public class Database {
public static Connection createConnection() throws NamingException,
SQLException {
Connection conn = null;
try{
Context ctx = new InitialContext();
if (ctx == null) {
throw new NamingException("No initial context");
DataSource ds = (DataSource) ctx.lookup("jdbc/OracleReports");
if (ds == null) {
throw new NamingException("No data source");
conn = ds.getConnection(); // here's exception when max connections to database
if (conn == null) {
throw new SQLException("No database connection");
} catch (NamingException e) {
e.printStackTrace();
throw new NoConnectionException();
} catch (SQLException e) {
e.printStackTrace();
throw new NoConnectionException();
catch (NullPointerException e) {
e.printStackTrace();
throw new NoConnectionException(); // obsluga bledy na wypadek jesli braknie wolnych polaczen do bazy
return conn;
}and at my ealier code i have error:
at logic.GetDataOracle.getrep_dws_wnioski_wstrzymane_graph(GetDataOracle.java:192)
at line: con = Database.createConnection();
in code:
public List getrep_dws_wnioski_wstrzymane_graph() {
int i = 0;
try {
con = Database.createConnection();
ps = (Statement) con.createStatement();
rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow");
while(rs.next()){
rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));
i++;
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
throw new NoConnectionException();
} finally {
try {
if(con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
throw new NoConnectionException();
return rep_dws_wnioski_wstrzymane_graph;
}so what's wrong?
i have limit max sessions 10 at oracle so i set at my connection pool 5 connections as max. But when i get max 5 sesssins and try to execute next query then i can't catch exception.. -
Does class Exception have an empty constructor
I thought every class you create in Java automatically creates an empty constructor regardless if you put one or not. I have a piece a class that extends Exception. In order to create a new object of my class using an empty constructor, I have to create it myself, unless I can call Exception's empty constructor.
A default empty constructor will be added to any class in which you don't declare your own constructor. See http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#16823
If the body of a constructor does not start with a call to another constructor, via super() or this(), the compiler will automatically add a call to super() at the start of the constructor. See http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#78435
I'm guessing you have your own Exception class that has a declared constructor like:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}You'll need to add your own empty constructor to this which calls super():
public class MyException extends Exception {
public MyException() {
super();
public MyException(String message) {
super(message);
} -
Catch exception inside function arguments
Class A is a core class in my application. When users create it with bad name format, they get an exception.
public class A{
public A(String name) throws FormatException{
// Check if the name the user entered is valid or not.
}But during the startup of my application I also create some instances of A. At startup time, any exception caught means that my source code is wrong: a bug on my own!
In this context I got myself with the following problem, how to catch an exception (that should not happen, because it comes from inside my source code) inside a function call:
// Create an instance of B that wraps A.
B b = B( new A("a_name_in_a_good_format") , some_other_parameter); // Possible exception from the constructor of A.Is there any way to catch that, or I'm obliged to create the instance of A before calling any function?
Edited by: ffrantz on Apr 1, 2010 10:15 AM
Edited by: ffrantz on Apr 1, 2010 10:17 AMThanks. I guess that is the only solution.
My problem is that I'm using that in the initialization of an enum, and there's no way to put that construction inside a try/catch block. Code looks like.
public static enum myReferenceInstancesToClone {
SIGNAL_MAGNITUDE(new C("mag"), some_other_parameters), // C extends A
SIGNAL_FREQUENCY(new D("freq"), some_other_parameters), // D extends A
RESISTIVITY (new A("R")), some_other_parameters),
INDUCTANCE (new A("L") , some_other_parameters),
CAPACITANCE (new A("C"), some_other_parameters);
// FIELDS
private A _referenceInstance;
private Object[] _refParameters; // A set of private fields that interest me
// METHODS
private OutputPropertiesA property, Object[] some_other_parameters){
_value = property;
_refParameters = some_other_parameters
// Other methods that are convenient to get fields.I'm doing it that way because i'm designing the data model for our application and it is uncertain what is the number and nature of properties that we will need to use. This construction with enums seemed good for me because:
1) Other designers can add properties in a single line. Without looking around on the rest of the source code.
2) The initialization process keeps probing the same enumeration, independent on the number/nature of the elements contained in it.
It is in this context that I cannot catch the exception thrown by the constructor of A:
public static enum myReferenceInstancesToClone {
SIGNAL_MAGNITUDE(new C("mag"), some_other_parameters), // Java compiler tells me I have an unhandled exception from 'new C()'
// ...If there is no way to catch that exception or propagate it.. then I'll do it with static arrays and static initialization blocks... but this means that I'll have to break my 'some_other_parameters' in different arrays. -
How to catch exception into a String variable ?
I have a code
catch(Exception e)
e.printStackTrace();
logger.error("\n Exception in method Process"+e.getMessage());
}when i open log i find
Exception in method Process null.
But i get a long error message in the server console !! I think thats coming from e.printStackTrace().
can i get the error message from e.printStackTrace() into a String variable ?
I want the first line of that big stacktrace in a String variable.
How ?A trick is to issue e.printStackTrace() against a memory-based output object.
void printStackTrace(PrintStream s)
// Prints this throwable and its backtrace to the specified print stream.
void printStackTrace(PrintWriter s)
// Prints this throwable and its backtrace to the specified print writer.Edited by: BIJ001 on Oct 5, 2007 8:54 AM -
How to catch exception while validating the username and password in hbm
Hi,
I do want to set the username and password dynamically in hibernate.cfg.xml
Here below is my configuration file.
{code<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>{code}
Also im getting that session factory object like the below code.
public class Sessions { private static SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); static { try { String userName = GuigenserviceImpl.userName; String password = GuigenserviceImpl.password; String hostName = GuigenserviceImpl.hostName; String portNo = GuigenserviceImpl.portNo; String sId = GuigenserviceImpl.sId; configuration .setProperty("hibernate.connection.username", userName); configuration .setProperty("hibernate.connection.password", password); configuration.setProperty("hibernate.connection.url", "jdbc:oracle:thin:@" + hostName + ":" + portNo + ":" + sId); try { configuration.configure("/hibernate.cfg.xml"); sessionFactory = configuration.buildSessionFactory(); GuigenserviceImpl.strAccpted = "true"; } catch (Exception e) { e.printStackTrace(); GuigenserviceImpl.strAccpted = "false"; } } catch (HibernateException hibernateException) { GuigenserviceImpl.strAccpted = "false"; hibernateException.printStackTrace(); } catch (Throwable ex) { GuigenserviceImpl.strAccpted = "false"; ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }
So, in this above scenario, suppose if im giving the wrong password means exception should be caught and the string variable "GuigenserviceImpl.strAccpted" should be assigned to false.
But im getting the SQL Exception only in console like wrong username and password. And finally i couldn't able to catch the exception in Sessions class, static block.
Anyone can help me in catching that SQL Exception in my Sessions class and i need to handle that SQL Exception in my class.
Im getting this following exception message in my console.
INFO: configuring from resource: /hibernate.cfg.xml Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Using Hibernate built-in connection pool (not for production use!) Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Hibernate connection pool size: 10 Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: autocommit mode: false Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@192.168.1.12:1521:orcl Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=scott, password=****} Apr 6, 2009 2:47:01 PM org.hibernate.cfg.SettingsFactory buildSettings WARNING: Could not obtain connection metadata java.sql.SQLException: ORA-01017: invalid username/password; logon denied at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70) at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:204) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399) at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:799) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:368) at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508) at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2073) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1298) at com.beyon.ezygui.server.Sessions.<clinit>(Sessions.java:39) at com.beyon.ezygui.server.GuigenserviceImpl.testRPC(GuigenserviceImpl.java:322) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Thanks in advance.
Thanks & Regards,
Kothandaraman N.Hi,
Myself hardcoded that username and password checking like the below code.
String name = loginData.get("userName").toString();
String pswd = loginData.get("pswd").toString();
String hstName = loginData.get("hName").toString();
String prtNo = loginData.get("portNo").toString();
String sid = loginData.get("sId").toString();
SessionFactory sessionFactory = null;
try {
if (name.trim().equals(userName) && pswd.trim().equals(password)
&& hstName.trim().equals(hostName)
&& prtNo.trim().equals(portNo) && sid.trim().equals(sId)) {
sessionFactory = Sessions.getSessionFactory();
strAccpted = "true";
} else {
strAccpted = "false";
} catch (Exception e) {
e.printStackTrace();
strAccpted = "false";
}I have my own values in string objects, then comparing that values with the values from login form. If both values are matching, then i will do configurations in hibernate.
ResourceBundle resourceBundle = ResourceBundle
.getBundle("com.beyon.ezygui.server.Queries");
public static final String connection_url = resourceBundle
.getString("connection.url");
public static final String userName = resourceBundle.getString("userName");
public static final String password = resourceBundle.getString("password");
public static final String hostName = resourceBundle.getString("hostName");
public static final String portNo = resourceBundle.getString("portNo");
public static final String sId = resourceBundle.getString("sId");The above are the String objects i'm checking for the match with values from login form.
Thanks & Regards,
Kothandaraman N. -
How to catch exception of JMS when call onMessage()?
I write a consumer client implement onMessage(),
in my main() method ...
try {
_adapter = new Adapter(checkConsumer,env);
_adapter.setSelector("client = 'Receive1'");
_adapter.start();
System.out.println("Hello...");
} catch(Exception e) {
_adapter = null;
System.out.println("Unable to start adapter: " + e.getMessage());
_adapter.start() will call onMessage() my onMessage like this
public void onMessage(Adapter adpt, Message message) {
try {
if(message instanceof TextMessage) {
// Write the text out as read String text = ((TextMessage)message).getText();
// Do CHECK Process adpt.demoOut("Receive CHECK Text is :" + text);
//System.out.println("class name is " + consumerName);
} else {
// This is just a message (no particular type) } } catch (Exception e) {
try {
adpt.warn("Error outputing data: " + message.getJMSMessageID());
} catch(Exception ignore) {
} adpt.warn("\tError: " + e.getMessage());
// Do some exception process }
If the JMS Server shutdown, how can I catch the exception?You might want to try with exception listener that JMS specification provides.
-
How to catch exception thrown from a function module?
Hi all,
When we are calling a function module from JSPDynpage setting some import parameters, If in some case an exception is thrown in the function module. How can we catch the same exception in the JSPDynpage program?
Thanks & Regards,
RaviHi Ravi
Try this
try
Object retMsgs = output.get(bapiretrunmsgobject);
if(result != null )
IrecordSet rmsg = (IrecordSet) result
catch(Exception ex)
printException(ex, "Error getting function result");
Lemme know for any further questions.
Regards
Praveen -
SFTP adapter error : Catching exception calling messaging system
Error: com.aedaptive.sftp.adapter.SFTPException : Not all messages were delivered succesfully
Could not deliver message to XI: com.sap.aii.af.lib.mp.module.ModuleException: senderChannel 'ca09269447583427adc545f8c23d244b': Catching exception calling messaging system
This is error message which i get in sender communication channel while working with SFTP adapter.Hi Pooja,
I think it would be better to add getcause() to get the cause of the issue.
Ref: http://help.sap.com/javadocs/pi/SP3/xpi/com/sap/aii/af/lib/mp/module/ModuleException.html
Thanks, -
Trying to inherit a super constructor
Lets suppose I have a parent and child.
public class Parent{
public Parent(String string){
//do some stuff here
public class Child{
and finally some other class using the child
pubilc class myChildTester{
pubilc static void main(String[] args){
Child child = new Child("heres a string");
//do some stuff with it
Now i completely understand that this itself wont work, since the child does not have that constructor. What I want to do is to somehow force the child to know enough to use the super constructor. However, I dont want to have to do something fancy like change the java compiler obviously. Also, no code is to be added to the child.
The reason I ask this is because in reality I have a similar situation. In that case though the parent has three different constructors the child needs. However the child only ever uses the "super" constructor, without adding any other functionality. Also, instead of just one child, I have maybe 100 different ones. I dont want to have to copy and paste the constructor that just calls "super" every single time. This is just pure laziness, but I see absolutely no reason why java wouldnt know enough to do this, since it does it already for the default constructor (and even that only works conditionally).
Also, doing something like making another method in the parent (i.e. like a getInstance(String string) method) that the child could use. I must have the constructor, because I'm using Spring to do some stuff on these classes.
I highly doubt there actually IS a way to do anything around this. But any suggestions would be appreciatedand no constructor with a super call.Well, the language is very clear: Constructors are not methods and not inherited.
You have the brittle superclass problem.
One way to handle your situation is to replace the constructors in the parent class with factory methods with the same parameter list as the constructor. In addtion the factory method is supplied information about which child should be created, like
class Parent {
public static Parent create(ChildType type, T1 p1, T2 p2) { // factory method
Parent p = null;
switch (type) { // create proper child
Cld1: p = new Child1(); break;
Cld2: p = new Child2(); break;
// do the constructors work
p.setP1(p1);
p.setP2(p2);
return p;
class Child1 extends Parent {
class Child2 extends Parent {
Parent p1 = Parent.create(Cld1, 0, 1);
Parent p2 = Parent.create(Cld2, 1, 0); -
Catch Exception shape - working in inner loop but not in outer loop
Hello,
I'm trying to use the catch exception shape for the first time. My orchestration has 3 loops. I'll call them loop1, loop2, loop3 where loop3 is my inner most loop. I'm able to catch the exact same error on the inner most loop3 but the outer
loop2 doesn't catch it and just puts a warning in the event viewer ( have no catch or scope on loop1 yet).
I can't figure out what the difference is.
The one that is not caught just has the dehydrated message and orchestration saying it will try again. then 5 mins later it does log an error and terminates but my catch is still not catching it.
Below in bold is the 'uncaught' warning message and the caught error message respectively. They look exactly the same to me, so why would the inner be caught but outer NOT caught? they're both catching the same type which is System.SystemException.
I couldn't get either to catch a System.FormatException but that's a different issue I'll solve later.
this is the warning from the UNCAUGHT error:
The adapter failed to transmit message going to send port "WcfSendPort_SqlAdapterBinding_TypedProcedures_dbo_uspEncounterAdd" with URL "mssql://sqldev1//AllianceDB?InboundId=uspEncounterAdd". It will be retransmitted after the retry interval
specified for this Send Port.
Details:"Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "sTransactionId" is invalid according to the expected SqlDbType BigInt. ---> System.FormatException: Input string was
not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Int64.Parse(String s, NumberStyles style, IFormatProvider provider)
at Microsoft.Adapters.Sql.MetadataHelper.ConvertXmlValueToDotNetObject(String xmlString, String fieldParameterName, SqlDbType sqlDbType, Int32 maxLength, Int32 precision)
--- End of inner exception stack trace ---
Server stack trace:
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)".
This is the error message that I'm writing to the event viewer when CATCHING the error in loop3:
Error from ScopeGetEncounterResponse: message = An error occurred while processing the message, refer to the details section for more information
Message ID: {1781C639-DB28-4306-B701-783E069A0403}
Instance ID: {8E1084F2-00EE-43B2-A112-BF80702A167A}
Error Description: Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "sRefID" is invalid according to the expected SqlDbType BigInt. ---> System.FormatException: Input string was not
in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Int64.Parse(String s, NumberStyles style, IFormatProvider provider)
at Microsoft.Adapters.Sql.MetadataHelper.ConvertXmlValueToDotNetObject(String xmlString, String fieldParameterName, SqlDbType sqlDbType, Int32 maxLength, Int32 precision)
--- End of inner exception stack trace ---
Server stack trace:
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
Thank you so much for your excellent advice!
Jean Stiles
jRenae.sIt turns out that my outer loop2 was catching the error. It was just retrying 3 times before it would catch it (I forgot that I had set the retry count to 0 on the loop3 inner port). I was so impatient that I was stopping my orchestration
before it was actually catching it!
jRenae.s
HI jRenae.s,
Congratulations! I’m glad to hear that you have solved this issue by yourself, and it is very appreciated to share your solution to us. It will be helpful for others, and welcome to post your question on this forum.
Best regards
Angie
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.
Maybe you are looking for
-
Trying to install the new app for iPhoto and is now paused and I can't get it working
In the process of downloading the iPhoto app and got stalled and is now stuck on "paused" and I can't get it to "unpause" and download the app. What should I do?
-
Why does it take 12 hours to process a 2 hr. in imovie 11
Why does it take 12 hours to process a 2 hr movie to quick time?
-
Retrieve data from entity bean to struts and display in JSP
I am integrating Struts+EJB3.0. Now i need to retrieve data stored in mysql database through entity bean to struts framework*(Action Form*).Then i need to display it in JSP page.(display using combo box). Please Any one give suggestions!!!!! Thanks i
-
Hi all, I would like read my content view into the method "onactionlink" linked to my outbound plug and pass it into a variable like this: data: lo_view type ref to if_wd_view. Is there anyone that can suggest me the code to use please? Thanks GN
-
I have purchased an Ambient Content movie. It successfully downloaded to my Itunes library. It did a sync with my Apple TV. whn I try to play the movie, I get a message that states, Your Apple TV is not aurthorized to play this content. My questions