answersLogoWhite

0


Best Answer

There could be an exception which cannot reach the user as it looks, instead it could be replaced by some other exceptions. In this case, the only solution is to write out our own exception and show the details regarding that exception.

Exceptions could be thrown inside a Web Service for various reasons. The possible types of exceptions that could be thrown are RuntimeException, RemoteException, SOAPFaultException and User Defined Exception.

Java supports exception handling by its try-catch constructs. Exceptions are conditions which the JVM or applications developed in Java are unable to handle. The Java API defines exception classes for such conditions. These classes are derived from java.lang.Throwable class. User-defined exceptions are those exceptions which an application provider or an API provider defines by extending java.lang.Throwable class.

The Web Service developer might try throwing a RuntimeException such as NullPointerException or ArrayIndexOutOfBoundsException inside the Web Service. But, throwing RuntimeException inside the Web Service is considered to be a bad exercise because RuntimeException will always be converted into RemoteException at the client side. While the client is waiting to catch the RuntimeException after invoking a Web Service, he will get only the RemoteException instead of RuntimeException. Eventually, he cannot perform proper error handling for RuntimeException.

The problem with throwing RemoteException is that the different client side libraries will interpret this exception in different ways. It is not portable.

The appropriate exception that the Web Service application could throw is SOAPFaultException. The SOAPFaultException contains four parts: faultcode, faultstring, actor, and detail. This exception can give you the complete information about the error condition. The faultcode might tell you whether the error has happened because of the Server, Client, or something else. For example, when a client doesn't provide security information such as username and password in the HTTP/SOAP header but the service mandates them, the pre-processing logic in the service implementation might obviously throw an authentication exception. This kind of error is considered to be a Client error. The faultstring contains the corresponding description of the error condition that has happened. This string message is human readable and the developer can easily debug the problem with the help of it. The detail element contains the actual exception message and its complete stack trace.

Actually, the detail element is an instance of the javax.xml.soap.Detail class and can be created by using the javax.xml.soap.SOAPFactory.createDetail() API.

User-Defined Exceptions Although SOAPFaultException gives necessary information that is needed to debug the problem, the Web Service client might want to do something more with a fault message that he had received. The one thing that he might want to do is to have a configurable and dynamic text description of the error that occurred. The other thing could be to have the internationalization support for the error messages. By providing text description in languages other than English, he could try addressing needs of all set of people. The list may grow more and more.

To achieve the previously stated goals, a user-defined exception with some specific format could be thrown in the service. Based on the exception that the client has received, he can decide what to do with fault message. The user-defined exception thrown inside the Web Service is directly mapped into wsdl:fault element in the Web Services Description Language (WSDL) of the Web Service. You could see the fault element as one of the child elements of operation element of the portType. The other two child elements of operation are input and output. The fault element, an optional field in the operation element, defines the abstract format of the error message that might be thrown by the Web Service. The wsdl:message element pertaining to WSDL:fault can contain only one message part, and the message part could be either a complexType or simple XMLType.

I propose here how a user-defined exception, MyCustomException, could be defined to better handle error messages. The MyCustomException contains an appropriate fault message that is as defined in the WSDL definition. The fault message contains the following three parts:

Error Code, containing a five-letter identifier plus a three-digit identifier

For example, GENEX001 could mean a generic error, whereas AUTEX001 could mean an authentication error.

Text describing the fault, including substitution variables (mentioned as {0}, {1}, and so forth)

For example, the corresponding text description for Error Code GENEX001 will be something like "Number that you have entered is {0}."

A list of values corresponding to the substitution variables defined in the above text.

For example, for the above case, the variable list will contain only one value (say 1) because the text description above contains only one substitution variable.

After processing the text using relevant logic, the final text description would be "Number that you have entered is 1." With the above approach:

Faults can be identified, using the error code, without the need for applications or people to parse or understand the fault text (which may be in a unknown language). Text description can be defined in many languages, and corresponding variables can be placed accordingly in a language-independent manner. Internationalization support can be offered by the Services by providing alternate language forms of fault messages automatically by replacing the text description portion only. Sample: Service, Exception Class, WSDL, and Client In this section, you will see a sample for service, exception, WSDL, and client. These samples will use Weblogic implementation.

Service Implementation This service takes two inputs: int number and String message. If the number is 1, SOAPFaultException will be thrown. If the number is 2, MyCustomException will be thrown; otherwise, the method will return successfully.

package WS.exception; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.Detail;

public class ExceptionService{ public String echo(int number, String message) throws MyCustomException{ System.out.println("Number: "+number+", Message: " + message); switch(number){ case 2: throw new MyCustomException( "GENEX001", "Number that you have entered is {0}", new String[]{String.valueOf(number)} ); case 1: Detail detail = null; try{ detail = SOAPFactory.newInstance().createDetail(); //add error message here detail.addTextNode( "Choice 1 means SOAPFaultException"); }catch(SOAPException ex){ throw new MyCustomException( "SEREX001", "Error while creating detail element", new String(){}); }

throw new javax.xml.rpc.soap.SOAPFaultException( new javax.xml.namespace.QName("env.Server"), "Number that you have entered is "+number, "NO ACTOR", detail); }

return "SUCCESS"; } }

I would like to make you understand the concept using a very simple code import java.lang.RuntimeException; class MyException extends RuntimeException { MyException(String str) { super(str); }

}

class testRunTime { void calculate() throws MyException { try { int x=0; int i=10/x;

}catch(MyException e) { e.printStackTrace();

} }

public static void main(String aa[]) { testRunTime tt=new testRunTime(); tt.calculate(); } }

just copy paste these code and run to understand what's the logic behind it with cheers Maneesh K Sinha ph-91-9867302855

Since Java is an Object Oriented programming language, it allows inheritance of all kinds of classes including Throwable classes.

For example, if you are building a website where users log in and buy stuff, you don't want your system to break down if a user has an expired credit card. You probably don't want to ignore that either.

public class CreditCardExpiredException extends Exception{...}

This special exception is thrown manually since it is user-defined.

public void login () throws CreditCardExpiredException, UserDoeNotExistException { if ( CreditCardExpired() ) { throw new CreditCardExpiredException() ; } if ( FileNotFound() ) { throw new UserDoeNotExistException() ; } }

public void Initializer () { try { login() ; } catch ( CreditCardExpiredException ex ) { /** @todo Handle this exception */ } catch ( UserDoeNotExistException ex ) { /** @todo Handle this exception */ } }

Where CreditCardExpiredException and UserDoeNotExistException are user defined Exceptions (extend the class Exception)

You have to handle or declare checked exceptions in Java.

To handle an exception you use a try catch block such as:

try {

BufferedReader in = new BufferedReader(new FileReader("filename"));

catch(IOException) {

System.out.println("Caught IO Exception");

}

To declare an exception

public static void raiseException throws IOException {

BufferedReader in = new BufferedReader(new FileReader("filename"));

}

For user defined exceptions one extends from Throwable as follows:

class MyThrowable extends Throwable { };

public class TestThrow {

public static void main(String... args) {

try {

testMethod(-10);

} catch (MyThrowable my) {

System.out.println("Something is wrong");

}

}

public static void testMethod(int i) throws MyThrowable {

// throw if i < 0

if (i < 0) {

throw new MyThrowable();

}

}

}

User Avatar

Wiki User

8y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

19y ago

UserDefined exceptions helps throwing an error page depending on the business logic. Suppose that i want to add a user to the system but at the same time somebody has already added the same user and in such senario i want to show a specif error page to the user so i will extend from the ExceptionClass and make a new class and then in my business class i will check the condition and if the user already exists i will throw a nee insatance of my own defined exception class.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

Any behaviour of a program that is unexpected is know as exception. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

For Details :

http://javamindmaps.blogspot.com/2011/02/blog-post.html

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

Some of the common exceptions you may encounter are:

1. ArrayIndexOutOfBoundsException - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).

2. ClassCastException - Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

3. IllegalArgumentException - Thrown when a method receives an argument formatted differently than the method expects.

4. IllegalStateException - Thrown when the state of the environment doesn't match the operation being attempted, e.g., using a Scanner that's been closed.

5. NullPointerException - Thrown when attempting to access an object with a reference variable whose current value is null.

6. NumberFormatException - Thrown when a method that converts a String to a number receives a String that it cannot convert.

7. AssertionError - Thrown when a statement's boolean test returns false.

8. ExceptionInInitializerError - Thrown when attempting to initialize a static variable or an initialization block.

9. StackOverflowError - Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)

10. NoClassDefFoundError - Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

Some of the common exceptions you may encounter are:

1. ArrayIndexOutOfBoundsException - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).

2. ClassCastException - Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

3. IllegalArgumentException - Thrown when a method receives an argument formatted differently than the method expects.

4. IllegalStateException - Thrown when the state of the environment doesn't match the operation being attempted, e.g., using a Scanner that's been closed.

5. NullPointerException - Thrown when attempting to access an object with a reference variable whose current value is null.

6. NumberFormatException - Thrown when a method that converts a String to a number receives a String that it cannot convert.

7. AssertionError - Thrown when a statement's boolean test returns false.

8. ExceptionInInitializerError - Thrown when attempting to initialize a static variable or an initialization block.

9. StackOverflowError - Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)

10. NoClassDefFoundError - Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Need to extend the Exception class or an Exception sub-class to create a custom Exception class.

Example:

public class MyException extends Exception {

public MyException() {

super();

}

public MyException(String msg) {

super(msg);

}

public MyException(Exception e) {

super(e);

}

public MyException(String msg, Exception e) {

super(msg, e);

}

}

Now MyException can appear in the throw or catch statement of a class.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

java.lang.Exception is the default class for handling exceptions. Normally, you use subclasses so that you can deal with specific errors.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How to create a custom exception in Java?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

How an exception subclass is created in java explain?

We can create a exception sub class by extending Exception class available in java


When should we use exception handling in java?

Exception handling should be used in Java in all cases where you as a programmer suspect that your code might throw some exceptions or create errors that might look ugly when a user is using the application. In such cases you use exception handling to catch and handle the exception and exit gracefully. You use the try - catch block in Java for exception handling.


Who create Java and when?

Who create Java &amp; when? Why he create java ? What are mane functions of it?


What is the purpose of NoMatchException handling method in java?

java exception


Can a class extend exception?

Yes You can. The features of such a class would be similar to what an Exception would have but not exactly as a predefined Java Exception. When you create a user defined exception you extend the java.lang.Exception class which in turn extends the java.lang.Throwable so indirectly you are extending the Throwable class while creating a user defined exception...


Which exception is thrown by the add method of Collection interface in java?

exception


What is difference between exception handling in C and Java?

Easy: there is no exception-handling in C.


Can you create a constructor for an interface in java?

NO, we cannot create a contructor for an interface in java.


Which is the base class of exception handling in java?

Thorwable


How do you throw exception in java?

we do it using the throw keyword.


How do you create setup of core java project?

how to create setup file in core java


Write the 3 user defined exception in java?

1. Arithmetic Exception 2. Input Output Exception 3. Number Format Exception