Constructor can throw exception or Not ?
Anybody please tell me if the constructor throws an exception or not ?
Please reply soon
Thanks
Amitindia
A constructor can throw an Exception. However I
would suggest throwing the generic Throwable, Error,
Exception or RuntimeException rather than a specific
exception is bad practice and you should choose an
appropirate exception to throw.All depends on wich kind of exception you are throwing,checked or unchecked. It's an even worse form to throw a RE, Error, or Throwable when you are throwing in fact a checked exception.
Nevertheless, I do agree, you must always strive to not throw exceptions, of any kind, in your construtor code. Construtors should be simple and reliable. Unles you have a very compelling reason to not do it, try to isolate the risky parts of the code where they are called ofter object construction or class loading.
May the code be with you.
Similar Messages
-
OracleConnection.ClearAllPools() throws exception Operation not valid due t
My app allows new logons so during the app startup I call my general "new logon" procedure that among other things does a ClearAllPools.
OracleConnection.ClearAllPools() throws exception "Operation not valid due to current state of the object".
I have converted from
System.Data.OracleClient.OracleConnection
to
Oracle.DataAccess.Client.OracleConnection
Did not have any problem when using the former.According to the documentation, ClearAllPools() throws an exception if there's no connection pool to clear. Most likely in that case the System.Data.OracleClient version is just not doing anything instead.
You should just be able to catch InvalidOperationException() at that point and ignore it. -
Constructors and throwing Exception
It seems that a constructor cannot throw an Exception.
What can I do if I need it to throw an Exception? Alternatives?You can throw an Exception in a constructor. Post some code, and maybe we can help you sort through the problem.
:o) -
I can throw exception from a catch
Hello,
I have created a new Exception : myException (for example).
and, i can't throw it under a catch bloc !!
My code :
public myMethod( ... ) throw myException {
try {
if(true) thorw new NullPointerException("test nll pt");
} catch(NullPointerException nullPt) {
if(true) throw new myException("toto",nullPt.getMessage());
this code doesn't want to throw "myException" from the "catch" !
Why ?
myException extends the class Exception.
Thanks.
maxx.First, I assume you didn't cut and paste the code, as what you have there won't compile. Can you 1) paste the actual code and 2) be a bit more specific about what's happening?
Aside from a couple of misspellings, I don't see why it wouldn't throw myException. Is it not compiling? Running but not throwing any exception? Throwing a different exception? -
Class with private constructor can be extended or not
Hi All,
I have a doubt.
if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
Thanks
SumitKaranjit wrote:
If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
public class Sabre20090603a
static class Fred extends Sabre20090603a
Fred()
super();
private Sabre20090603a()
} -
Hi Team,
Problem : we are getting below exception on vs-2012 "Method not found: 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag CrystalDecisions.ReportAppServer.ReportDefModel.ISCRExportOptions.get_ExportOptionsEx()'"
Could you please help me why we are getting this Error?
Note : Im not using Exportstream method , just using only Export method (refer code sample) for exporting Crystal report.
EnvironMent Details :
Crystal Report Version : CRforVS_13_0_5.exe
(SAP Crystal Reports runtime engine for >net Framework (64-bit)
SAP crystal Reports ,version for Microsoft Visual studio)
OS -Windows 7 -64 BIT
RAM : 16 GB
code where i Got the Exception
dfdoFile.DiskFileName = Path.Combine(reportPath, reportFileName);
expOptions.ExportDestinationType = ExportDestinationType.DiskFile;
expOptions.ExportFormatType = ExportFormatType.CrystalReport;
expOptions.DestinationOptions = dfdoFile;
objReport.Export(expOptions);
below is stack trace :
at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.Export(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.Export(ExportOptions options)
at Medtech.BaseObjects.Report.CreatePDF(ReportClass objReport, DataView objRptDataView, String printerName, PrinterPaperOrientation
i have attached Screenshot for your reference ,Hi Sandeep
You are using Service Pack 5 (Crystal Report Version : CRforVS_13_0_5.exe). I'd like you to update your install to SP 13:
SAP Crystal Reports, developer version for Microsoft Visual Studio: Updates & Runtime Downloads
and test.
- Ludek
Senior Support Engineer AGS Product Support, Global Support Center Canada
Follow me on Twitter -
Core dump on throwing exception
Hi,
I am using an exception class derived from C++ standard exception class (MyException). In this, I am having a member variable of type std::string. I am using this in a DLL that is being used by Java application using JNI.
In my C++ code, I am catching exception following way:
catch(XException& exp)
catch(MyException& exp)
catch(exception& exp)
If I am using std::string as member in MyException class, it results in a coredump whatever exception is thrown (MyException or any other unknown exception supposed to be caught in the standard exception class.). Note that this happens in release build of my dll and never repeatable in debug build.
This problem occurs only in Solaris (tested both in Solaris 7 and Solaris 8). It does not occur in Windows.
Now, if I use char array instead of std::string the problem does not occur!!!! Exceptions are caught properly.
If anyone can throw more light on why usage of std::string causes issues in exception handling in Solaris using CC 5.0 compiler, it shall be of help. I feel problem might be due to not updating the patches related to CC 5.0 exception handling. Also, is it a good practise to use std::string in exception handling classes?C++ 5.0 is very old and is no longer supported. Patches are still available for it, however. You should get the latest patches from
http://access1.sun.com/sundev
and see if that solves your problem. If not, you should upgrade to a supported compiler release.
The standard string class can perfrom dynamic memory allocation and can throw exceptions. It's not ideal for use in exception handling for those reasons. But for ordinary situations when you are not out of memory it' s probably OK. -
Throw exception in Java mapping and handle this in BPM
Hi,
I'll use a Java mapping in a BPM transform step. Is it possible to throw an exception inside this Java mapping and handle this in a BPM exception handler?
thanks and regards
VerenaHi Verena,
In a BPM transformation step, I think you can throw exceptions only for system errors.
Let me explain with an example, one of the ways to handle your scenario:
Lets assume your Java Mapping fails then you can trap that exception in your Java mapping and compose an XML message which indicates that an error has occurred.
say for e.g.
<intermediateStructure>
<SatusDocument>
<StatusCode>ERROR</StatusCode>
<ErrCode>123</ErrCode>
<ErrDesc><!populate the thrown exception details></ErrDesc>
</StatusDocument>
<Payload>
<!contains actual XML message with data>
</Payload>
</intermediateStructure>
if Java mapping is Successful, you can compose the XML message as follows:
<intermediateStructure>
<SatusDocument>
<StatusCode>SUCCESS</StatusCode>
<ErrCode>0</ErrCode>
<ErrDesc></ErrDesc>
</StatusDocument>
<Payload>
<!contains actual XML message with data>
</Payload>
</intermediateStructure>
You can use BPM switch operation to switch to different processing branches say for e.g. "error" branch or "success" branch by examining the value of <StatusCode> tag.
Hope it helps !
Regards,
Sridhar -
Custom Indirection Container throwing exception in constructor
Hi I've following the how-to and implemented my own custom indirection container. However, when reading an object from the database I'm getting the following exception. I'm guessing that it could be related to having null references stored as 0 in id columns. Any help would be greatly appreciated.
Thanks,
Jon
Exception thrown in main Exception [TOPLINK-152] (OracleAS TopLink - 10g (9.0.4.8) (Build 050712)):
oracle.toplink.exceptions.DescriptorException
Exception Description: The operation [buildContainer constructor (null) Failed: java.lang.NullPointe
rException] is invalid for this indirection policy [oracle.toplink.internal.indirection.ContainerInd
irectionPolicy@cc0e01].
Mapping: oracle.toplink.mappings.OneToOneMapping[ryFromMail]
Descriptor: Descriptor(com.peoplesoft.crm.omk.design.PsRyedocVar --> [DatabaseTable(PS_RYEDOC_VAR)])
Local Exception Stack:
Exception [TOPLINK-152] (OracleAS TopLink - 10g (9.0.4.8) (Build 050712)): oracle.toplink.exceptions
.DescriptorException
Exception Description: The operation [buildContainer constructor (null) Failed: java.lang.NullPointe
rException] is invalid for this indirection policy [oracle.toplink.internal.indirection.ContainerInd
irectionPolicy@cc0e01].
Mapping: oracle.toplink.mappings.OneToOneMapping[ryFromMail]
Descriptor: Descriptor(com.peoplesoft.crm.omk.design.PsRyedocVar --> [DatabaseTable(PS_RYEDOC_VAR)])
at oracle.toplink.exceptions.DescriptorException.invalidIndirectionPolicyOperation(Descripto
rException.java:669)
at oracle.toplink.internal.indirection.ContainerIndirectionPolicy.buildContainer(ContainerIn
directionPolicy.java:62)
at oracle.toplink.internal.indirection.ContainerIndirectionPolicy.valueFromQuery(ContainerIn
directionPolicy.java:254)
at oracle.toplink.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java
:898)
at oracle.toplink.mappings.OneToOneMapping.valueFromRow(OneToOneMapping.java:1302)
at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:876)
at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder
.java:164)
at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:322)
at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:
242)
at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:368)
at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:510)
at oracle.toplink.queryframework.ReadQuery.execute(ReadQuery.java:125)
at oracle.toplink.publicinterface.Session.internalExecuteQuery(Session.java:1962)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086)
at oracle.toplink.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolic
y.java:254)
at oracle.toplink.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java
:898)
at oracle.toplink.mappings.OneToOneMapping.valueFromRow(OneToOneMapping.java:1302)
at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:876)
at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder
.java:164)
at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:322)
at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:
242)
at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:368)Clients of your class might not like you throwing
exceptions from the ctor. If they're checked
exceptions it'll mean try/catch blocks. If there are
LOTS of checked exceptions that'll mean lots of catch
blocks. Could get messy fast. You could catch in the
ctor and wrap in a subclass of
java.lang.RuntimeException. Those are unchecked, like
java.lang.IllegalArgumentException.I would strongly advise against making your checked exceptions unchecked just so that the caller's code will compile without try/catch blocks. Either way--checked or unchecked--if I do Foo foo = new Foo();
foo.doStuff(); I won't get to doStuff() if the ctor threw an exception.
You'd throw unchecked exceptions in those cases where it's appropriate--e.g., the caller passed you invalid args (bad code on the caller's part, appropriated for unchecked exception), or the VM couldn't get enough memory to create your object (probably not something the caller can do anything about, so, again, appropriate for unchecked).
But if, for example, he's passing you database login parameters that an end user provided, and the password is wrong or the host is unreachable, then you'd want to throw a checked exception, because it's not bad code on the caller's part, and there might be something he can do to recover.
Note that the example of the incorrect password above is quite different from the "invalid args" example in the previous paragraph. Your method would throw IllegalArgumentException if the caller passed args that violate your method's precondition--e..g. lie outside some range of numbers. That is, it's a value that your method simply can't use. A bad password for a db login, on the other hand, is legal as far as your method is concerned, it just failed authentication in the db.
@%: I know you're aware of the proper use of checked/unchecked exceptions, but the way you worded you post kind of sounded like you were saying, "just use unchecked if you find the caller has too many try statements."
¶ -
JUnit test fixture where constructor of base object throws exception
I'm trying to construct a test case which requires an object whose constructor currently throws and exception (it tries to make a connection which isn't currently available).
Now normally the trick would be to construct a test fixture class which extends the base class and returns the stuff I want. The trouble is I can't cope with an exception in in super constructor. Is there any way out of this, short of refactoring the offending base class?Just use the no-arg constructor of RootRenderingContext, and all should be defaulted appropriately.
-
Web part throwing exception at run time but not in debug mode
The below code is throwing exception at run time but does not throw exception while debugging in Visual Studio. This is really causing difficulty for me to detect the cause of exception. Below I have also placed the exception image for reference.
namespace CheckforContractorLogin.VisualWebPart1
public partial class VisualWebPart1UserControl : UserControl
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
string loginName = string.Empty;
string coc_url = string.Empty;
SPQuery spQuery = new SPQuery();
spQuery.Query = "<Where><Eq><FieldRef Name='LoginName' /><Value Type='Text'>" + currentUser + "</Value></Eq></Where>";
Guid _spSiteID = SPContext.Current.Site.ID;
Guid _spWebID = SPContext.Current.Site.OpenWeb().ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
using (SPSite _spSite = new SPSite(_spSiteID))
using (SPWeb _spWeb = _spSite.OpenWeb(_spWebID))
//if user has already accepted the COC
SPList getSPList = _spWeb.Lists["RedirectUrl"];
SPListItemCollection getspItemColl = getSPList.Items;
foreach (SPListItem item in getspItemColl)
if (Convert.ToString(item["Title"]) == "Policy Acceptance")
coc_url = Convert.ToString(item["Url"]);
SPList spList = _spWeb.Lists["Policy Acceptance Status"];
SPListItemCollection spItemColl = spList.GetItems(spQuery);
bool result = getADUserInfo();
if ((spItemColl.Count == 0) && (result))
Response.Redirect(coc_url);
protected string currentUser
get
string currentUser1 = HttpContext.Current.User.Identity.ToString();
int index = currentUser1.IndexOf("\\") + 1;
string currentLoginUser = currentUser1.Substring(index);
return currentLoginUser;
protected bool getADUserInfo()
DirectoryEntry dentry = null;
DirectorySearcher dsearcher = null;
string ldap = string.Empty;
string empID = string.Empty;
string _empID = string.Empty;
try
Guid spSiteGUID = SPContext.Current.Site.ID;
Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
SPList spList = elevatedWeb.Lists["LDAP_Paths"];
SPQuery spQuery = new SPQuery();
spQuery.Query = "<Where><Eq><FieldRef Name='OU'/>"
+ "<Value Type='Text'>QD</Value></Eq></Where>";
SPListItem spItem = spList.GetItemById(1);
ldap = spItem["Path"].ToString();
dentry = new DirectoryEntry();
dentry.Path = ldap;
dentry.Username = "******\\sp_admin";
dentry.Password = "******";
dsearcher = new DirectorySearcher(dentry);
dsearcher.Filter = String.Format("(&(ObjectCategory=Person)(sAMAccountName=" + currentUser + "))");
SearchResult searchResult = dsearcher.FindOne();
dentry = searchResult.GetDirectoryEntry();
if (searchResult != null)
if (dentry.Properties.Contains("physicalDeliveryOfficeName"))
empID = dentry.Properties["physicalDeliveryOfficeName"][0].ToString();
if (empID.Contains("QA-"))
return true;
else
return false;
catch (Exception e)
throw e;
finally
dentry.Close();
dentry.Dispose();
dsearcher.Dispose();Hi Zakir,
I am not sure but it would be nice if you can do following
Try search ULS log with correlation id and find exact error and share here. If not able to find do following
Or in catch block write
Response.Write(ex.ToString());
and check what exception its giving. -
2 connections, either one can throw an exception
In my application I have 2 connections open to the different DBs at the same time. Either operation ( select/update etc ) can throw an exception. I don't want to embrace every SQL statement with the different "try ... catch" block, because it will be too messy. Is there any way to determine what connection threw an exception.
Sample :
try{
Connection conn1 = ...
Connection conn2 = ...
PreparedStatement ps1 = conn1.getPreparedStatement(...);
PreparedStatement ps2 = conn2.getPreparedStatement(...);
ps1.executeQuery(qstring1);
ps2.executeQuery(qstring2);
catch ( SQLException ex){
// Can I put some logic here which will tell me whether the problem related to conn1 or conn2 ?
System.out.println("Exception : " + ex);
}vs777 wrote:
I have a "global" DB instance where my metadata and instance-specific data resides ( domestice data ). I also have "secondary" DB instance with ( foreign data ) to which I might connect at the run-time if the application logic requires. I am updating metadata Sounds like you want to do "change data capture". If that's the case, I'd recommend looking into your database vendor's capabilities rather than doing this in Java. I'd also look into database links and triggers if your database supports them. Sounds like you're doing something that's best left to the database, not your application. It could be done behind the scenes. It sounds like more of a pure database play rather than business logic.
throughout the application "metadata"? What does that word mean to you? Please explain.
So you're changing the schema dynamically? Metadata means describing the tables and columns. That's changing as the app runs? Sounds confusing.
as well as retrieve and update data in one of the instances depending on conditions, so it's really inconvinient for me to wrap every SQL statement ( execute/select/delete method ) with "try ... catch" block.Inconvenient, but necessary. Somebody has to handle exceptions.
Sounds like you need to think about a way to not repeat code.
I have an application up-and-running for several months already and "2 DB instances" requirement came up just recently, so I am not planning to redesign an application but to handle SQL exceptions properly.So what do you want here? What are you asking if you're not willing to redesign anything?
You're probably not even aware of two phase commit. What happens to your app if the insert of the data succeeds but the metadata does not? Ooops, out of synch. Do you roll back manually? How does the app alert you to the need to do so?
% -
How can I deal with the "throw exception"?
A function has the following definition:
import javax.naming.NamingException;
public BinRelation readBinRelation() throws BadInputDataException,IOException
When I use this function as follows:
BinRelation binRel;
binRel = readBinRelation();
then comes the error:
unreported exception javax.naming.NamingException; must be caught or declared to be thrown.
So how can use this function correctly?
ThanksSo how can use this function correctly?By learning what exceptions are, how they're used, and what you can do to deal with them. There's a tutorial here: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.htmlAnd here's a quick overview:
The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled. -
EJB is not throwing exception to calling Action class in Unix environment
Hi
We are using Weblogic Server 9.2.3.0.
One of our EJB is not throwing exception to calling Action class in Unix environment. Its working fine in Windows.
Somehow the EJB is swallowing the exception.
any idea? I suspect it may be environmental issue?
thank youHi
We are using Weblogic Server 9.2.3.0.
One of our EJB is not throwing exception to calling Action class in Unix environment. Its working fine in Windows.
Somehow the EJB is swallowing the exception.
any idea? I suspect it may be environmental issue?
thank you -
Java Does Not Throw Exception When Writing To Read-Only Files
I have noticed that when I try to write to a read-only file in a window environment, Java does not throw an IOExcpetion, it just dosn't write to the file.
I am writing an FTP server and here is the code:
public static long copyStream(InputStream in, OutputStream out)throws IOException
IOException exception = null;
long copied = 0;
try
byte buffer[] = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
copied += read;
catch(IOException e)
//ensures that the streams are closed.
exception = e;
try
in.close();//ensures output stream gets closed, even if there is an
//excption here.
catch(IOException e){exception = e;}
out.close();//try to close output.
if(exception != null)
//exception is not null, an exception has occured.
//rethrow exception.
throw exception;
return copied;//all ok, return bytes copied.
}Is this a bug in JAVA VM? Is so, how should I report it?I have noticed that when I try to write to a read-only file in a window environment,
Java does not throw an IOExcpetion, it just dosn't write to the file.C:\source\java\Markov>attrib readonly.out
A R C:\source\java\Markov\readonly.out
�C:\source\java\Markov>java b
java.io.FileNotFoundException: readonly.out (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at b.main(b.java:5)
import java.io.*;
public class b {
public static void main(String[] args) {
try {
OutputStream os = new FileOutputStream ( "readonly.out");
catch (Exception e) {
e.printStackTrace();
}
Maybe you are looking for
-
Is there any plan for an enterprise version of adobe cloud?
-
When I start ttm(http://code.google.com/p/ttm/) (via terminal) I get this: Using locale: (null) and ttm doesn't start further. I have configured my locales in rc.conf. Does anybody know what's wrong?
-
Help with slideshow thumbnail?
I would like to use only an enlarged section of my slideshow hero image as my thumbnail. This Muse Site of the Day does it like that: http://www.rocketdc.com/index.html#ourwork Anyone have any idea how they pulled this off?
-
Hi All, We have two node servers, UBB and DM confile file info as follows. UBB : # MULTI DOMAIN template *RESOURCES IPCKEY 0xabe7 DOMAINID ARS MASTER ARS_A,ARS_B MAXACCESSERS 6000 MAXSERVERS 500 MAXSERVICES 6000 MODEL MP OPTIONS LAN,MIGRATE SCANUNIT
-
How can i delete my chat history
how can i delete my chat history