Creating your own Exception Subclasses

Java defines a class called Exception, which represents generic unexpected events.Subclasses define specific unexpected events.There are two general categories of exceptions: checked and unchecked. Unchecked exceptions descend from Run time Exception and Error, which are subclasses of Exception.
You should leave unchecked exceptions to Java.That is, you should always throw checked exceptions, never subclasses of Run time Exception or Error. You can look through the APIs for the different types of checked and unchecked exceptions that Java defines. 
The difference between a checked and unchecked exception is that you do not have to wrap the call to a method that might throw an unchecked exception in a try/catch block, while you must do so for a checked exception. But unchecked exceptions will halt your thread just the same as checked exceptions if you do not catch them.
Your subclass don't need to actually implement anything .it is their existence in the type system that allows you to use them as exceptions.The Exception class does not define any methods of its own .It does of course inherit those methods provided by throw able .Thus all exceptions ,including those that you create have the methods defined by throw able available to them .

Here is a listing of some of the more common exceptions in Java and where they might occur:

Method
Description
Throwable fillInStackTrace Returns a Throwable objectthat contains a completed stack trace.This object can be rethrown
Throwable initCause(Throwable causeexc) Associates causeExc with the invoking exception as a cause of the invoking exception.Returns a reference to the exception
String getLocalized Message() Returns a localizes description of the exception
String getMessage() Return a description of the exception
void printStackTrace(PrintWriter stream) Sends the stac trace to the specified Stream
void printStackTrace() Displays the stack trace
void printStackTrace(PrintStream stream) Sends the stack trace to the specified Stream
void setStackTrace(StackTraceElement elements[]) Sets the stack trace to the elements passed in elements.This method specialized applications,not normal use
String toString Returns a String object containing a description of the exception .This method is called by prinln() when outputting a throwable object
AclNotFoundException ActivationException
AlreadyBoundException ApplicationException
AWTException BackingStoreException
InvalidMidiDataException InvalidPreferencesFormatException
GeneralSecurityException GSSException
Throwable getCause() Returns the exception that underlies the current exception .if there is no underlying exception null is returned
BadAttributeValueExpException BadBinaryOpValueExpException
BadLocationException BadStringOperationException
ClassNotFoundException CloneNotSupportedException
RefreshFailedException RemarshalException
RuntimeException SAXException
TimeoutException TooManyListenersException
LastOwnerException LineUnavailableException
TransformerException TransformException
DataFormatException DatatypeConfigurationException
DestroyFailedException ExecutionException
ExpandVetoException FontFormatException
BrokenBarrierException CertificateException
InstantiationException InterruptedException
IntrospectionException InvalidApplicationException
IllegalAccessException IllegalClassFormatException
InvalidTargetObjectTypeException InvocationTargetException
IOException JAXBException
JMException KeySelectorException
MarshalException MidiUnavailableException
MimeTypeParseException MimeTypeParseException
NamingException NoninvertibleTransformException
NoSuchFieldException NoSuchMethodException
NotBoundException NotOwnerException
ScriptException ServerNotActiveException
SOAPException SQLException
StackTraceElement[] getStackTrace() Returns an array that contains the stack trace.One element at atime as an array of StackTraceElement. The method called before the exception was thrown.This method is found in the first element of the array.The StackTraceElement class gives your program access to information about each element in the trace
ParseException ParserConfigurationException
PrinterException PrintException
PrivilegedActionException PropertyVetoException
UnmodifiableClassException UnsupportedAudioFileException
UnsupportedCallbackException UnsupportedFlavorException
UnsupportedLookAndFeelException URIReferenceException
XMLSignatureException XMLStreamException
URISyntaxException UserException
XAException XMLParseException


Program : ExceptionDemo.java
import java.io.*;
class Myexception extends Exception
{
    private int detail;
    Myexception(int a)
    {
     detail=a;
    }
    public String toStrng()
     {
      return "Myexception["+detail+"]";
     }

}
class ExceptionDemo
{
    static void compute (int a) throws Myexception
    {
     System.out.println("called compute ("+a+")");
     if(a>10)
     throw new Myexception(a);
     System.out.println("Normal exit");
    }
    public static void main(String arg[])
     {
         try
        {

            
         compute(1);
         compute(20);
        }
         catch(Myexception e)
        {
         System.out.println("caught "+e);
        }
     }
}
This exaple defines a subclass of Exception called MyException .This subclass is quite simple.It has only a constructor plus an overloaded toString() method that displays the value of the exception .The ExceptionDemo class defines a method named compute() that throws a MyException object.The exception is thrown when compute() integet parameter is greater than 10 .The main method sets up an exception handler for MyException ,then calls compute() with a legal value and an ilegal one to show both paths through the code


Output


Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]


Creating your own Exception Subclasses



5 comments:

Mounika said...

I am commenting to let you know what a terrific experience my daughter enjoyed reading through your web page. She noticed a wide variety of pieces, with the inclusion of what it is like to have an awesome helping style to have the rest without hassle grasp some grueling matters.
python training Course in chennai
python training in Bangalore
Python training institute in bangalore

Xplore IT Corp said...

Hi, thanks for your blog, if you want to learn about programming languages like java, php, android app, embedded system etc. I think this training institute is the best one.
Best java training in coimbatore
Android training in coimbatore
Networking training in coimbatore

Anu said...

Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
DevOps Training | Certification in Chennai | DevOps Training | Certification in anna nagar | DevOps Training | Certification in omr | DevOps Training | Certification in porur | DevOps Training | Certification in tambaram | DevOps Training | Certification in velachery

lavanya said...

When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

Java training in Chennai

Java Online training in Chennai

Java Course in Chennai

Best JAVA Training Institutes in Chennai

Java training in Bangalore

Java training in Hyderabad

Java Training in Coimbatore

Java Training

Java Online Training

jeni said...

Wow, amazing weblog format! How lengthy have you been running a blog for? you make running a blog look easy. The total glance of your website is wonderful, let alone the content!


data science training in chennai

data science training in velachery

android training in chennai

android training in velachery

devops training in chennai

devops training in velachery

artificial intelligence training in chennai

artificial intelligence training in velachery

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org