1

I have tried for a couple of days researching on how to create a custom exception in a try/catch.

Here is what I am attempting to do:

I have an included JS file in my html page. The JS file defines a custom object, as well as defining methods for the object.

Next, in the html page I am doing the following:

try {
   MyObj = new CustomObj;     //from the included JS file.
   MyObj.CustomMethod();      //also from the included JS file.
} catch(e) {
   alert("Error in either the create of the object, or the method. Error is " + e.description)
}

I need to be able, within the code for the CustomMethod(), to set the Error Object's properties that are captured in the catch statement. For example:

  CustomMethod = function{
     try{
       document.getelementById("field1").value = "my value";
     } catch(err) {
       //Set the return error
       ReturnErr.description = "There was an error!";
     }
  };

Can this be done? From what I have tried, I have used the throw statement, but it does not effect the Error Object, thus the catch section is never triggered. In face, the custom message is only shown in the Console.

Thanks ahead of time.

1

1 Answer 1

2

Try:

function MyException(_message, _data) {
    this.message = _message;
    this.data = _data;
    this.name = "MyException";
}

Usage

try{
      //...                   
   }
   catch(_error){
      throw new MyException(message, _error);
   }

Hope it will help you to sort things out

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But I guess that I cannot modify the (_error) in your example?
@EricMeans, sorry, typo, pass error as second parameter.
Sorry, what I meant was not to have to use the throw in the catch block, but to set the error that the catch block gets, in the called function/method from the try block. Does that make any sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.