+ All Categories
Home > Documents > JAVA-CH5

JAVA-CH5

Date post: 08-Apr-2018
Category:
Upload: neha-naik
View: 216 times
Download: 0 times
Share this document with a friend

of 23

Transcript
  • 8/7/2019 JAVA-CH5

    1/23

    CH.5 INHERITANCEInheritance is one of the important concept of object orientedprogramming because it allows the creation of hierarchicalclassifications. Using inheritance, you can create a general class thatdefines traits common to a set of related items. This class can then

    be inherited by other, more specific classes, each adding those thingsthat are unique to it. In the terminology of Java, a class that is inheritedis called a superclass. The class that does the inheriting is called asubclass. Therefore, a subclass is a specialized version of a superclass.It inherits all of the instance variables and methods defined by thesuperclass and adds its own, unique elements. Java supports 4inheritances:

    1. simple inheritance2. hierarchical inheritance3. multilevel inheritance4. multiple inheritance ( indirectly with the help of interfaces )

    INHERITANCE BASICS:To inherit a class, you simply incorporate the definition of one classinto another by using the extends keyword.// A simple example of inheritance.// Create a superclass.class A{

    int i, j;void showij(){ System.out.println(i and j :+ i + + j); }

    }

    // Create a subclass by extending class A.class B extends A{

    int k;void showk(){ System.out.println(k: + k); }

    void sum(){ System.out.println(i+j+k: + (i+j+k)); }

    }

    class Simplelnheritance{

    public static void main(String args[]){

    A superOb = new A();B subOb = new B();

  • 8/7/2019 JAVA-CH5

    2/23

    superOb.i = 10;superOb.j = 20;

    System.out.println(Contents of superOb:);superOb.showij();

    /* The subclass has access to all public members its superclass.*/

    subOb.i = 7;subOb.j = 8;subOb.k = 9;System.out.println(Contents of subOb:);subOb.showij();subOb.showk();System.out.println(Sum of i, j and k in subOb:);subOb.sum();

    }}

    The output from this program is shown here:Contents of superOb:i and j: 10 20Contents of subOb:i and j: 7 8k: 9Sum of i, j and k in subOb:i+j+k: 24

    Even though A is a superclass for B, it is also a completelyindependent, stand-alone class. Being a superclass for a subclass doesnot mean that the superclass cannot be used by itself. Further, asubclass can be a superclass for another subclass.

    The general form of a class declaration that inherits a superclass isshown here:class subclass-name extends superclass-name{

    // body of class

    }You can only specify one superclass for any subclass that you create.Java does not support the inheritance of multiple superclasses into asingle subclass.If the super class has private variables, we can access them bycreating a separate method for them.For ex:class A

  • 8/7/2019 JAVA-CH5

    3/23

    {private:int i, j;void getdata(int a, int b){

    i=a;j=b;}

    }

    USING SUPER:Whenever a subclass needs to refer to its immediate superclass, it cando so by use of the keyword super. super has two general forms. Thefirst calls the superclass constructor. The second is used to access amember of the superclass that has been hidden by a member of asubclass.

    USING SUPER TO CALL SUPERCLASS CONSTRUCTORS:A subclass can call a constructor method defined by its superclass byuse of the following form of super:super(parameter-list);Here, parameter-list specifies any parameters needed by theconstructor in the superclass. super( ) must always be the firststatement executed inside a subclass constructor.

    Super.memberThe second form of super acts like a this keyword except that it refers

    to the immediate super class of the sub class in which it is used. It ismostly applicable to the situations in which the member names of thesub class hides the members of the super class. The member can beeither a method or instance variable.Ex:class A{

    int i;private:int j;A(int x, int y)

    { j = x;i = y;

    }void display(){

    System.out.println(i);System.out.println(j);

    }

  • 8/7/2019 JAVA-CH5

    4/23

    }class B extends A{

    int a;B(int x, int y, int z)

    { super(x, y);I = z;

    }void display(){

    super.display();System.out.println(a);

    }}class Main

    {public static void main(String args[]){

    B b1 = new B(10,20,30);b1.display();

    }}

    USING ABSTRACT CLASSES:Sometimes you will want to create a superclass that only defines ageneralized form that will be shared by all of its subclasses, leaving it

    to each subclass to fill in the details. Such a class determines thenature of the methods that the subclasses must implement and arecalled as abstract classes. One way this situation can occur is when asuperclass is unable to create a meaningful implementation for amethod.

    Any class that contains one or more abstract methods must also bedeclared abstract. To declare a class abstract, you simply use theabstract keyword in front of the class keyword at the beginning of theclass declaration. There can be no objects of an abstract class. That is,an abstract class cannot be directly instantiated with the new operator.Such objects would be useless, because an abstract class is not fullydefined. Also, you cannot declare abstract constructors, or abstractstatic methods. Any subclass of an abstract class must eitherimplement all of the abstract methods in the superclass, or be itselfdeclared abstract.Ex:abstract class A{

  • 8/7/2019 JAVA-CH5

    5/23

    abstract void callme()// concrete methods are still allowed in abstract classesvoid callmetoo(){ System.out.println(This is a concrete method); }

    }

    class B extends A{void callme(){ System.out.println(Bs implementation of callme); }

    }class AbstractDemo{

    public static void main(String args[]){

    B b = new B();b.callme();

    b.callmetoo();}

    }Although abstract classes cannot be used to instantiate objects, theycan be used to create object references, because Javas approach torun-time polymorphism is implemented through the use of superclassreferences. Thus, it must be possible to create a reference to anabstract class so that it can be used to point to a subclass object.

    USING FINAL WITH INHERITANCE:The keyword final has three uses. First, it can be used to create theequivalent of named constant. The other two of final apply toinheritance.

    FINAL TO PREVENT OVERRIDING:While method overriding is one of Javas most powerful features, therewill be times when you will want to prevent it from occurring. Todisallow a method from being overridden, specify final as a modifier atthe start of its declaration. Methods declared as final cannot beoverridden.class A{ final void meth()

    { System.out.println(This is a final method); }

    }class B extends A{

    void meth()// ERROR Cant override.{ System.out.priritln(Illegal); }

    }Because meth() is declared as final, it cannot be overridden in B. If youattempt to do so, a compile-time error will result.

  • 8/7/2019 JAVA-CH5

    6/23

    Methods declared as final can sometimes provide a performanceenhancement: The compiler is free to inline calls to them because itknows they will not be overridden by a subclass. When a small finalmethod is called, often the Java compiler can copy the bytecode for thesubroutine directly inline with the compiled code of the calling method,

    thus eliminating the costly overhead associated with a method call.Miming is only an option with final methods. Normally, Java resolvescalls to methods dynamically, at run time. This is called late binding.However, since final methods cannot be overridden, a call to one canbe resolved at compile time. This is called early binding.

    USING FINAL TO PREVENT INHERITANCE:Sometimes you will want to prevent a class from being inherited. To dothis, precede the class declaration with final. Declaring a class as finalimplicitly declares all of its methods as final, too. It is illegal to declarea class as both abstract and final since an abstract class is incompleteby itself and relies upon its subclasses to provide complete

    implementations.Here is an example of a final class:final class A{

    //body}// The following class is illegal.class B extends A // ERROR! Cant subclass A{

    //body}As the comments imply, it is illegal for B to inherit A since A is declaredas final.

    DEFINING INTERFACES:An interface is basically a kind of class. Like classes, interfaces containmethods and variables but with a major difference. The difference isthat interfaces define only abstract methods and final fields. Thismeans that interfaces do not specify any code to implement thesemethods and data fields contain only constants. Therefore, it is theresponsibility of the class that implements an interface to define thecode for implementation of these methods.

    The syntax for defining an interface is very similar to that for defining aclass. The general form of an interface definition is:interface InterfaceName{

    variables declaration;methods declaration;

    }

  • 8/7/2019 JAVA-CH5

    7/23

    Here, interface is the key word and InterfaceName is any valid Javavariable (just like class names). Variables are declared as follows:static final type VariableName = Value;All variables are declared as constants. Methods declaration willcontain only a list of methods without any body statements. Example:

    return-type methodNamel (parameter_list);Ex:interface item{

    static final int code = 1001;static final String name = Fan;void display ( );

    }The code for the method is not included in the interface and themethod declaration simply ends with a semicolon. The class thatimplements this interface must define the code for the method.

    EXTENDING INTERFACES:Like classes, interfaces can also be extended. That is, an interface canbe subinterfaced from other interfaces. The new subinterface willinherit all the members of the superint in the manner similar tosubclasses. This is achieved using the keyword extends as shownbelow:Interface name2 extends namel{

    body of name2}For example, we can put all the constants in one interface and themethods in the other. This will enable us to use the constants inclasses where the methods are not required. Example:interface ItemConstants{

    int code = 1001;string name = Fan;

    }interface Item extends ItemConstants{

    void display ( );}The interface Item would inherit both the constants code and nameinto it. Note that the variables name and code are declared like simplevariables. It is allowed because all the variables in an interface aretreated as constants although the keywords final and static are notpresent.We can also combine several interfaces together into a singleinterface.

  • 8/7/2019 JAVA-CH5

    8/23

    Ex: interface Item extends ItemConstants, ItemMethodsWhile interfaces are allowed to extend to other interfaces,subinterfaces cannot define the methods declared in thesuperinterfaces. After all, subinterfaces are still interfaces, not classes.Instead, it is the responsibility of any class that implements the derived

    interface to define all the methods. When an interface extends two ormore interfaces, they are separated by commas. It is important toremember that an interface cannot extend classes. This would violatethe rule that an interface can have only abstract methods andconstants.

    IMPLEMENTING INTERFACES:Interfaces are used as superclasses whose properties are inheritedby classes. It is therefore necessary to create a class that inherits thegiven interface. This is done as follows:class classname implements Interfacename

    {body of classname

    }Here the class classname implements the interface interfacename. Amore general form of implementation may look like this:class classname extends superclass implementsinterfacel,interface2{

    body of classname}This shows that a class can extend another class while implementing

    interfaces.When a class implements more than one interface, they are separatedby a comma.Ex:interface Area // Interface defined{

    final staticfloat pi = 3.14F;float compute (float x, float y);

    }class Rectangle implements Area // Interface implemented

    {public float compute (float x, float y)

    { return (x*y); }}class Circle extends Rectangle, implements Area //multipleinheritance{

    public float compute (float x, float y)

  • 8/7/2019 JAVA-CH5

    9/23

    { return (pi*x*y); }}

    class InterfaceTest{

    public static void main(String args[]){Rectangle rect = new Rectangle ( );Circle cir = new Circle( );Area area;area = rect;

    System.out.println(Area of Rectangle:+area.compute(lO,2O)):

    area = cir;System.out.println(Area of Circle:+ area.compute(lO,O);

    }

    }The Output is as follows:

    Area of Rectangle = 200Area of Circle = 314

    Any number of dissimilar classes can implement an interface. However,to implement the methods, we need to refer to the class objects astypes of the interface rather than types of their respective classes.Note that if a class that implements an interface does not implementall the methods of the interface, then the class becomes an abstractclass and cannot be instantiated.

  • 8/7/2019 JAVA-CH5

    10/23

    ACCESSING INTERFACE VARIABLES:Interfaces can be used to declare a set of constants that can be used in

    different classes. Since such interfaces do not contain methods, thereis no need to worry about implementing any methods. The constantvalues will be available to any class that implements the interface. Thevalues can be used in any method, as part of any variable declaration,or anywhere where we can use a final value. Example:interface A{

    int m = 10;int n = 50;

    }class B implements A

    {int x=m;void methodB(int size){

    . . . . . .if (size < n). . . . . .

    }}

    CH.6 EXCEPTION HANDLING

    INTRODUCTION:Rarely does a program run successfully at its very first attempt. It iscommon to make mistakes while developing as well as typing aprogram. A mistake might lead to an error causing the program toproduce unexpected results. Errors are the wrongs that can make aprogram go wrong.An error may produce an incorrect output or may terminate theexecution of the program abruptly or even may cause the system tocrash. It is therefore important to detect and manage properly all thepossible error conditions in the program so that the program will not

    terminate or crash during execution.TYPES OF ERRORS:Errors may broadly be classified into two categories: Compile-time errors Run-time errors

    COMPILE-TIME ERRORS:

  • 8/7/2019 JAVA-CH5

    11/23

    All syntax errors will be detected and displayed by the Java compilerand therefore these errors are known as compile-time errors.Whenever the compiler displays an error, it will not create the .classfile. It is therefore necessary that we fix all the errors before we cansuccessfully compile and run the program.

    Most of the compile-time errors are due to typing mistakes.Typographical errors are hard to find. We may have to check the codeword by word, or even character by character. The most commonproblems are: Missing semicolons Missing (or mismatch of) brackets in classes and methods Misspelling of identifiers and keywords Missing double quotes in strings Use of undeclared variables Incompatible types in assignments / initialization Bad references to objects

    Use of = in place of = = operator And so onOther errors we may encounter are related to directory paths. An errorsuch asjavac : command not foundmeans that we have not set the path correctly. We must ensure thatthe path includes the directory where the Java executables are stored.Errorl.java :7: ; expectedSystem.out.println (Hello Java!)^1 error

    RUN-TIME ERRORS:Sometimes, a program may compile successfully creating the .class filebut may not run properly. Such programs may produce wrong resultsdue to wrong logic or may terminate due to errors such as stackoverflow. Most common run-time errors are: Dividing an integer by zero Accessing an element that is out of the bounds of an array Trying to store a value into an array of an incompatible class or type Trying to cast an instance of a class to one of its subclasses Passing a parameter that is not in a valid range or value for a method

    Trying to illegally change the state of a thread Attempting to use a negative size for an array Using a null object reference as a legitimate object reference toaccess a method or a variable Converting invalid string to a number Accessing a character that is out of bounds of a stringAnd many more.

  • 8/7/2019 JAVA-CH5

    12/23

    Ex:class Error2{

    public static void main(String args[]){

    int a = 10;int b = 5;int c = 5;int x = a/ (bc); // Division by zeroSystem.out.println(x = + x);int y = a/(b+c);System.out.println(y = + y);

    }}

    output:

    java.lang.ArithmeticException: / by zeroat Error2 .main (Error2 .java:1O)When Java run-time tries to execute a division by zero, it generates anerror condition, which causes the program to stop after displaying anappropriate message.

    EXCEPTIONS:An exception is a condition that is caused by a run-time error in theprogram. When the Java interpreter encounters an error such asdividing an integer by zero, it creates an exception object and throwsit(i.e., informs us that an error has occurred).

    If the exception object is not caught and handled properly, theinterpreter will display an error message and will terminate theprogram. If we want the program to continue with the execution of theremaining code, then we should try to catch the exception objectthrown by the error condition and then display an appropriate messagefor taking corrective actions. This task is known as exception handling.The purpose of exception handling mechanism is to provide a means todetect and report an exceptional circumstance so that appropriateaction can be taken. The mechanism suggests incorporation of aseparate error handling code that performs the following tasks:1. Find the problem (Hit the exception).

    2. Inform that an error has occurred (Throw the exception)3. Receive the error information (Catch the exception)4. Take corrective actions (Handle the exception)The error handling code basically consists of two segments, one todetect errors and to throw exceptions and the other to catchexceptions and to take appropriate actions.

  • 8/7/2019 JAVA-CH5

    13/23

    Java exception handling is managed via five keywords: try, catch,throw, throws, finally. Program statements that you want to monitor forexceptions are contained within a try block. If an exception occurswithin the try block, it is thrown. Your code can catch this exception(using catch) and then throw it in some rational manner. System-

    generated exceptions are automatically thrown by Java run-timesystem. To manually throw an exception, use the keyword throw; Anyexception that is thrown out of a method must be specified as such bya throws clause. Any code that absolutely must be executed before amethod returns is put in finally block.This is the general form of an exception-handling block:try{

    // block of code to monitor for errors}catch (ExceptionTypel exOb)

    {// exception handler for ExceptionTypel

    }catch (ExceptionType2 exOb){

    // exception handler for ExceptionType2}// . . . . . . . . .finally{// block of code to be executed before try block ends

    }

    Exception Type Cause of ExceptionArithmeticException Caused by math errors such as

    division by zero

  • 8/7/2019 JAVA-CH5

    14/23

    ArraylndexOutOfBoundsException Caused by bad all indexesArrayStoreException Caused when a program tries to

    store the wrong type of data in anarray

    FileNotFoundException Caused by an attempt to access a

    nonexistent filelOException Caused by general I/O failures,such as inability to read from a file

    NullPointerException Caused by referencing a null objectNumberFormatException Caused when a conversion

    between strings and number failsOutOfMemoryException Caused when theres not enough

    memory to allocate a new objectSecurityException Caused when an applet tries to

    perform an action not allowed bythe browsers security setting

    StackOverflowException Caused when the system runs outof stack space

    StringlndexOutOfBoundsException Caused when a program attemptsto access a nonexistent characterposition in a string

    class Error3{

    public static void main(String args []){

    int a = 10;int b= 5;

    int c = 5;int x, y;try{

    x = a / (bc); // Exception here}

    catch (ArithmeticException e){

    System.out.println(Division by zero);y = a / (b+c);

    System.out.println (y =+y);}

    }}output:Division by zeroy = 1

  • 8/7/2019 JAVA-CH5

    15/23

    MULTIPLE CATCH CLAUSES:In some cases, more than one exception could be raised by a singlepiece of code. To handle this type of situation, you can specify two ormore catch clauses, each catching a different type of exception. Whenan exception is thrown, each catch statement inspected in order, and

    the first one whose type matches that of the exception is executed.After one catch statement executes, the others are bypassed, andexecution continues after the try/catch block. The following exampletraps two different exception types:

    Ex:class Multicatch{

    public static void maln(String args[]){

    try

    {int a = args.length;System.out.println(a = + a);int b = 42 / a;int c[ ] = { 1 };c[42] = 99;

    }catch (ArithmeticException e){

    System.out.println(Divide by 0: + e);}

    catch (ArraylndexOutOfBoundsException e){

    System.out.println(Arrayindexoutofbound: + e);}

    System out println( After try/catch blocks);}

    }

    This program will cause a division-by-zero exception if it is started with

    no command- line parameters, since a will equal zero. It will survivethe division if you provide a command-line argument, setting a tosomething larger than zero. But it will cause anArraylndexOutOfBoundsException, since the int array c has a length of1, yet the program attempts to assign a value to coutputC:\>java MultiCatcha=0

  • 8/7/2019 JAVA-CH5

    16/23

    Divide by 0: java.larig.ArithmeticException: / by zeroAfter try/catch blocks.

    C:\>java MultiCatch TestArga=l

    Arrayindexoutofbound: java.lang.ArrayAfter try/catch blocks

    THROW:It is possible for your program to throw an exception explicitly, usingthe throw statement. The general form of throw is shown here:throw Throwableinstance;Throwableinstance must be an object of type Throwable or a subclassof Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used asexceptions. There are two ways you can obtain a Throwable object:

    using a parameter into a catch clause, or creating one with the newoperator.The flow of execution stops immediately after the throw statement;any subsequent statements are not executed. The nearest enclosingtry block is inspected to see if it has a catch statement that matchesthe type of the exception. If it does find a match, control is transferredto that statement. If not, then the next enclosing try statement isinspected, and so on. If no matching catch is found, then the defaultexception handler halts the program and prints the stack trace.

    Class DemoThrow{

    static void demoproc(){

    try{

    throw new NullPointerException(demo);}catch(NullPointerException e)

    {System.out.println(Caught inside demoproc.);throw e; // rethrow the exception

    }}

    public static void main(String args[]){

  • 8/7/2019 JAVA-CH5

    17/23

    try{

    demoproc();}catch(NullPointerException e)

    { System. out .println (Recaught:);}

    }}output:Caught inside demoproc.Recaught: java.lang.NullPointerException: demo

    THROWS:If a method is capable of causing an exception that it does not

    handled, it must specify the behavior so that callers of the method canguard themselves against that exception. You do this by including athrows clause in the methods declaration. A throws clause lists thetypes of exceptions that a method might throw. This is necessary forall exceptions, except those of type Error or RuntimeException, or anyof their subclasses. All other exceptions that a method can throw mustbe declared in the throws clause. If they are not, a compile-time errorwill result.Syntax:type method-name(parameter-list) throws exception-list{

    // body of method}Exception-list is a comma-separated list of the exceptions that amethod can throw.

    class ThrowsDemo{

    static void throwOne() throws IllegalAccessException{

    System.out.println(Inside throwOne);throw new IllegalAccessException(demo);

    }public static void main(String args[]){

    try {throwOne ();

    }catch (IllegalAccessException e){

  • 8/7/2019 JAVA-CH5

    18/23

    System.out.println(Caught +e);}

    output:inside throwOnecaught java.lang.IllegalAccessException: demo

    FINALLY:When exceptions are thrown, execution in a method takes a ratherabrupt, nonlinear path that alters the normal flow through the method.Depending upon how the method is coded, it is even possible for anexception to cause the method to return prematurely. This could be aproblem in some methods. For example, if a method opens a file uponentry and closes it upon exit, then you will not want the code thatcloses the file to be bypassed by the exception-handling mechanism.The finally keyword is designed to address this contingency.finally creates a block of code that will be executed after a try/catch

    block has completed and before the code following the try/catch block.The finally block will execute whether or not an exception is thrown. Ifan exception is thrown, the finally block will execute even if no catchstatement matches the exception. Any time a method is about toreturn to the caller from inside a try/catch block, via an uncaughtexception or an explicit return statement, the finally clause is alsoexecuted just before the method returns. This can be useful for closingfile handles and freeing up any other resources that might have beenallocated at the beginning of a method with the intent of disposing ofthem before returning. The finally clause is optional. However, each trystatement requires at least one catch or a finally clause.

    class FinallyDemo{

    static void procA(){

    try{

    System.out.println(inside procA);throw new RuhtimeException(demo);

    }

    finally{

    System.out .println(procAs finally);}

    }static void procB(){

  • 8/7/2019 JAVA-CH5

    19/23

    try{

    System.out.println(inside procB);return;

    }

    finally{

    System.out.println(procBs finally);}

    }static void procC(){

    try{

    System.out.println(inside procC);

    }finally{

    System.out.println(procCs finally);}

    }public static void main(String args[]){

    try{

    procA ();

    }

    catch (Exception e){ System.out.println(ExceptiOn caught); }

    procB ();procC ();

    }}output:inside procA

    procAs finallyException caughtinside procBprocCs finallyinside procCprocCs finally

    JAVAS BUILT-IN EXCEPTIONS:

  • 8/7/2019 JAVA-CH5

    20/23

    Inside the standard package java.lang. Java defines several exceptionclasses. The most general of these exceptions are subclasses of thestandard type RuntimeException. Since java.lang is implicitly importedinto all Java programs, most exceptions derived fromRuntimeException are automatically available. Furthermore, they need

    not be included in any methods throws list. In the language of Java,these are called unchecked exceptions because the compiler does notcheck to see if a method handles or throws these exceptions. Javadefines several other types of exceptions that relate to its various classlibraries.

    Exception MeaningArithmeticException Arithmetic error, such as divide-by-

    zero.ArrayIndexoutOfBoundException Array index is out-of-bounds.

    ArrayStoreException Assignment to an array element of an incompatible type.

    ClassCastException Invalid cast.IllegalArgumentException Illegal argument used to invoke a

    method.IllegalMonitorStateException Illegal monitor operation, such as

    waiting on an unlocked thread.IllegalStateException Environment or application is in

    incorrect state.IllegalThreadStateException Requested operation not

    compatible with current thread

    state.IndexOutOfBoundsException Some type of index is out-of-bounds.NegativeArraySizeException Array created with a negative size.NulPointerException valid use of a null reference.NumberFormatException Invalid conversion of a string to a

    numeric format.SecurityException Attempt to violate security.StringIndexOutOfBound Attempt to index outside the

    bounds of a stringUnsupportedOperationException An unsupported operation was

    encountered.ClassNotFoundException Class not found.CloneNotSupportedException Attempt to clone an object that

    does not implement the Cloneableinterface.

    IllegalAccessException Access to a class is denied.InstantiationException Attempt to create an object of an

    abstract class or interface.

  • 8/7/2019 JAVA-CH5

    21/23

    InterruptedException One thread has been interruptedby

    another thread.NoSuchFieldException A requested field does not exist.NoSuchMethodException A requested method does not exist.

    CREATING YOUR OWN EXCEPTION SUBCLASSES :Although Javas built-in exceptions handle most common errors, youwill probably want to create your own exception types to handlesituations specific to your applications. This is quite easy to do: justdefine a subclass of Exception (which is, of course, a subclass ofThrowable. Your subclasses dont need to actually implement anythingit is their existence in the type system that allows you to use them asexceptions.The Exception class does not define any methods of its own. It does, ofcourse, inherit those methods provided by Throwable. Thus, all

    exceptions, including those that you create, have the methods definedby Throwable available to them.Methods of Throwable class are as follows:1. Throwable filllnStackTrace()Returns a Throwable object that contains a completed stack trace. Thisobject can be rethrown.2. StackTraceElement[ ] getStackTrace()Returns an array that contains the stack trace, one element at a timeas an array of StackTraceElement. The method at the top of the stackis the last method called before the exception was thrown. Thismethod is found in the first element of the array. The

    StackTraceElement class gives your program access to informationabout each element in the trace, such as its method name. Added byJava 2, version 1.4.void printStackTrace()Displays the stack trace.4. void printStackTrace(PrintStream stream)Sends the stack trace to the specified stream.5. void printStackTrace(PrintWriter stream)Sends the stack trace to the specified stream.6. void setStackTrace(StackTraceElement Elements[ ])Sets the stack trace to the elements passed in elements. This method

    is used for specialized applications, not normal use. Added by Java 2,version 1.4.String toString()Returns a String object containing a description of the exception. Thismethod is called by println( ) when outputting a Throwable object.

    THROWING OUR OWN EXCEPTIONS:

  • 8/7/2019 JAVA-CH5

    22/23

    There may be times when we would like to throw our own exceptions.We can do this by using the keyword throw as follows:throw new Throwable_subclass;

    Ex:

    import java. lang.Exception;class MyException extends Exception{

    MyException(String message){

    super(message);}

    }class TestMyException{

    public static void main(String args[])

    {int x = 5, y = 1000;try{

    float z = (float) x / (float) y;if(z < 0.01)

    throw new MyExcepton(Number is toosmall);

    }catch (MyException e){

    System.out.println(Caught my exception);System.out.println(e.getMessage( ) );

    }finally{

    System.out.println(I am always here);}

    }}

  • 8/7/2019 JAVA-CH5

    23/23


Recommended