Wrapping exceptions thrown in super/this constructor calls into other exceptions

I want the api of my module to only throw MyPackageSpecificException whenever anything goes wrong and the module unable to perform its task. (The original exception will be given as the cause of the MyPackageSpecificException).

Now, for one constructor I needed an URL as a parameter to locate a resource. I would also like to make an alternative constructor to which a String representation of the URL can be given:

public MyClass(String urlString) throws MalformedURLException{ this(new URL(urlString)); }

As the URL constructor throws MalformedURLException, I want to wrap it into a MyPackageSpecificException by doing:

public MyClass(String urlString) throws MyPackageSpecificException{ try{ this(new URL(urlString)); } catch (MalformedURLException e){ throw new MyPackageSpecificException(e); } }

But, the above is not valid, since the super() or this() constructor call must occur on the first line of the constructor.

The same problem applies if the super() or this() constructor throws an exception which I want to wrap into something else.

How should I solve this? Or is what I am trying to do bad practice?

-------------Problems Reply------------

Try the following:

public class MyClass
{
private URL url;

public MyClass(URL url)
{
this.url = url;
}

public MyClass(String urlString) throws MyPackageSpecificException
{
this(toURL(urlString));
}

private static URL toURL(String urlString) throws MyPackageSpecificException
{
try
{
return new URL(urlString));
}
catch (MalformedURLException e)
{
throw new MyPackageSpecificException(e);
}
}
}

If it fits your code, you can use a static creator method instead:

private MyClass(String urlString) { ... }

public static MyClass createMyClass(String urlString) throws MyPackageSpecificException {
try {
new MyClass(urlString);
catch (Exception e) {
throw new MyPackageSpecificException(e);
}
}

Instead of using this() have a common init() method that takes the URL argument that way it does not need to be the first line of the constructor.

public MyClass(String url) throws MyPackageSpecificException
{
try
{
init(new URL(url));
}
catch (MalformedURLException e)
{
throw new MyPackageSpecificException(e);
}
}

public MyClass(URL url)
{
init(url);
}

private void init(URL url)
{
// do constructor work here
}

Category:java Views:0 Time:2009-08-14

Related post

  • While constructing the default constructor can not handle exception : type Exception thrown by implicit super constructor 2011-07-21

    The code works fine until I try to make the code into a constructable class. When I attempt to construct an object from it I get the error "Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define

  • Configure Websphere not to wrap RuntimeExceptions thrown from Filter.doFilter 2010-08-11

    When working with Websphere 7.0, RuntimeExceptions thrown from the Filter.doFilter are wrapped in a ServletException, instead of being propagated as they are. Is there any way of configuring Websphere to throw the original exception instead of wrappi

  • c# Exception Thrown at (not in) Constructor 2011-10-24

    An exception is being thrown at (not in) a constructor call: controller = new Controller(classInstance); // Won't let me step in, exception thrown immediately. The exception description is: System.BadImageFormatException: Could not load file or assem

  • JSR 303, ValidationException not thrown when using default constructor in POJO 2011-11-11

    The first and second test succed (which means a validation was thrown), but the third test fails. Because of requirements of a framework I am using, I have to have a default-constructor for my POJO. As seen in the second test, the validation does wor

  • Log exceptions thrown by WCF service constructor? 2012-04-11

    Is there any way to capture and log exceptions thrown from a WCF service's constructor? Creating a custom IEndpointBehavior with a custom IErrorHandler seems to catch all exceptions except those thrown during service construction. (Please correct me

  • What does an IsolatedStorage_Operation_ISFS error thrown from the IsolatedStorageFileStream constructor mean? 2010-07-25

    I have a Silverlight 4 application (plug... http://audioorchard.com ...end plug) that is occasionally throwing an exception in the IsolatedStorageFileStream constructor. System.IO.IsolatedStorage.IsolatedStorageException: [IsolatedStorage_Operation_I

  • Will using new (std::nothrow) mask exceptions thrown from a constructor? 2009-12-09

    Assume the following code: Foo* p = new (std::nothrow) Foo(); 'p' will equal 0 if we are out of heap memory. What happens if we are NOT out of memory but Foo's constructor throws? Will that exception be "masked" by the nothrow version of 'new' and 'p

  • Wrap exceptions by runtime exceptions with an annotation 2009-06-27

    Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically? @MagicAnnotation // no throws clause! void foo() { throw new Exception("bar")' } --------------Solutions------------- No way to do that, at

  • How to define an explicit constructor for an url object in Java 2012-03-24

    I am defining a url in processing (or java) with the line: URL base = new URL("http://www.google.com/"); So I get the following error: Default constructor cannot handle exception type MalformedURLException thrown by implicit super constructor. Must d

  • Try/catch blocks inside constructors 2010-02-18

    Is it a bad programming practice to have try/catch blocks inside constructors? Or does it make no difference as long as our programs handle typeinitializer exceptions gracefully. In C# if there are any exceptions inside a constructor the framework al

  • failed constructor and failed destructor in C++ 2010-02-26

    I have one question about failed constructor and failed destructor in C++. I noticed that when the constructor failed, an exception will be thrown. But there is no exception thrown in destructor. My question is 1) If constructor failed, what exceptio

  • COM+: ApplicationException instead of thrown exception 2010-09-23

    I got a ASP.net webservice which calls a COM+ component. A class in the COM+ component throws an exception which I want to handle. But ApplicationException is caught by the webbservice instead of the real exception. Why is that? Edit: Exception detai

  • Constructor help with const C-string array 2010-09-30

    I have a simple class Name: class Name { private: char nameStr[30]; public: Name(const char * = ""); char * getName() const; void print() const; }; I am having two problems, which are just a bit difficult for me wrap my head around. The constructor i

  • help me wrap up a slider into a function I can call 2010-12-20

    A while ago I posted a question about a jquery slider here This now works a treat but I now need to wrap it up in a function for each day of the week so I can pass in values as some of the values are hard coded. I've tried doing this and Firebugs tel

  • Access modifier for default constructor in LINQ2SQL generated classes 2011-07-09

    Just beginning with LINQ2SQL here and I have a few questions. I have db with a single table Customer, I run sqlmetal and it generates an ORM class for me. I'd like to apply certain rules in the constructor of Customer, maybe something like the firstN

  • Why constructors will always have same name as of class and how they are invoked implicitly? 2011-08-08

    I want to know that why the name of constructor is always same as that of class name and how its get invoked implicitly when we create object of that class. Can anyone please explain the flow of execution in such situation? --------------Solutions---

  • Destructor not called when an exception is thrown 2012-01-28

    Consider the following code: #include <iostream> using namespace std; class Test { static int count; int id; public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Te

  • Why throwing exception in constructor results in a null reference? 2012-04-12

    Why throwing exception in constructor results in a null reference? For example, if we run the codes below the value of teacher is null, while st.teacher is not (a Teacher object is created). Why? using System; namespace ConsoleApplication1 { class Pr

  • Why is Class.newInstance() "evil"? 2008-10-12

    Ryan Delucchi asked here in comment #3 to Tom Hawtin's answer: why is Class.newInstance() "evil"? this in response to the code sample: // Avoid Class.newInstance, for it is evil. Constructor<? extends Runnable> ctor = runClass.getConstructor();

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.148 (s). 11 q(s)