0% found this document useful (0 votes)
15 views47 pages

Java CHP 4 Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
15 views47 pages

Java CHP 4 Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
a 42 JAVA PROGRAMMING (DIP. gey ty 4 grem ran successflly at its very first attempt. It fs Common to make mina, 7 ly does @ program mm. A mistake might lead to an error causing the Program ty » gram. A mis ig : ‘ake that can make incorrect program. a Java's exception-handling mechanism. An exception is an abnormal developi as well as typing 2 unexpected res This chapter also exami Condi. . In other words, exception is a run-time error. In computer langusge that arises in a code sequence at run ti do not support exception handling, errors must be checked and handled manually. hithreaded Unlike most other computer languages, java provides built in support for multithreade: Programming multithreaded program contain two ‘or more parts that can run concurrently. Each part of such program is calle, thread, and each thread defines a separate path of execution. ERRORS ‘The wrongs or mistakes that can make program go wrong is called as errors, ° Errors may be logical or may be typing mistakes, * An error may produce an erroneous or incorrect ouput or may terminate the execution of the progan abruptly or even may cause the system to crash, * So it is important to detect and manage all error Conditions in the program so that the program wil sa terminate or crash during execution, 4.2.1 TYPES OF ERRORS SL AYPES OF ERRORS : Lt aR Qu. What are different types of errors? 12,14 2M) Errors may broadly classified into two categories : (1) Compile-time errors (2) Run-time errors a) Compile-time errors ; © Allsyntax errors compile time errors, * Whenever the compiler displays an Srror, it will not [Link], It is therefore Recessary that we fix all the errors before we can successfully compile and run the program. Example : Itustration of compile-time errors, /* This program contains an error */ class Error | { Public static void main (String args []) { [Link] printin(“Hello java!" V/missings } } ee p- Text Book Series 7 JAVA PROGRAMMING (DIP. V SEM. [Link]) he java compiler does a nice job of The jave comple doc ¢ job of telling us where the errors are in the program. ple, if we have missed the semi sed the semicolon at the end of print statement in example, the following For © message Will be displayed on the screen : Error 1. Java: 7: “y'expected [Link] (“Hello Java!”) error We can now go to the appropriate line, correct the crror, and recompile the program. Sometimes a single a may be the source of multiple errors later in the compilation. For example, use of an undeclared variable ‘i il i : in a number of places will cause a series of errors of “undefined variable”. c : adie We should generally consider the earliest errors as the major source of our problem. ‘After we fix such an error, we should recompile the program and look for other errors. Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We may have to check the code word by word, or even character by character. The most common problems are : @ Mi semicolons Gi)Missing (or mismatch of) brackets in classes and methods. (iii) Misspelling of identifiers and keywords. (iv) Missing double quotes in strings. (¥) Use of undeclared variables. (vi) Incompatible types in assignments/ initialization (vii) Bad references to objects. (viii) Use of = in place of == operator and so on. Other errors we may encounter are related to directory paths. An error such as Java C : command not found means that we have not set the path correctly. We must ensure that the path includes the directory where the java executables are stored. fully creating the class file but may not run properly. (2) Run-time errors logic or may terminate due to errors such as stack Sometimes, a program may compile succes + Such programs may produce wrong results due to wrong overflow. common runtime 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. iv) 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. vi) Trying to illegally change the state of a th vil) Attempting to use a negative size for an array. i te 10 access a method or a variable. ill) Using a null object reference as a legitimate object reference X) Connecting invalid string to a number. . ) Accessing a character that is out of bounds of a strin; read. * When such errors are encountered, java typically generates an crror message and aborts the program. Example : Illustration of run-time errors class Error? { Public static void main (String args [}) { inta= 10; int b=5; inte=5; int x= al(b-c); Mivision by zero [Link](“x =" + x); nt y = a(b+c); [Link](*y =” + y); } } Above program is syntactically correct and therefore does not cause any problem during compilation, However, while executing, it displays the following message and stops without executing further statement. [Link]. ArithmeticException:/by zero at [Link] (Error 2,java : 10) When java run-time tries to execute a division by zer0, it generates an error condition, which causes the program to stop after appropriate message. isplaying an 4.3 EXCEPTION $-09 (2M) Q2. What is exception? Give different types of| exception that could occur during runtime. S-12 (6M) <-Wel3 2M) Q.1. What is an exception ? Q.3. Define an exception. Q.4. Mention any: two common Java exception and their cause. 5-13 (2M) 44 | JAVA PROGRAMMING (DIP. V SEM. Co ny * When the j such as dividing an integer by zero, it crey exception object and throws it (i.e. inform that an error has occurred), ferpreter encounters ay, If the exception objects is not caught and hang), properly, the interpreter will display ang, message as shown in the output of example of , time errors and will terminate the program, If we want the program to continue with y. execution of the remaining code, then we sho, tty to catch the exception object thrown by the isplay an appropriate message for taking corrective actions. This task is known as exception handling. The purpose of exception handling mechanism ig to provide a means to detect and report a “exceptional circumstance” so that appropr action can be taken. error condition and then The mechanism suggests incorporation of a separate 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). @) Receive the exception), error information (catch the (4) Take corrective actions (handle the exception) * The error handling code basically consists of two segments, one to detect error and to throw exceptions and the other to eateh exception take appropriate action, © When writ and to '8 Programs, we must always be ot the lookout for places in the program where an exception could be generated * Some common exception that we must watch out for catching are listed in table 4,3, Exception type “Arithmetic exception, Cause of exception Caused by math errors such as division by zero. « An exception is a condition that is caused by a run time error in the program. ‘ArrayIndexOutOF Caused by bad array BoundException, indexes, [BoundException, | indexes. Book Series 45 Caused when a program tries to store the wrong of data in an array, ‘aused by an att ace! npt to fille, (Caused by referencing a non exister - javaNested Try 2 Divide by 0 : [Link]:/by 2210, Case 3: a=2 C Spjava NestedTry. a=2 ArrayIndexOutOfBound. Nesting of try statements can occur in less obvious ways when methods calls are involved. In this case, the try within the method is still nested inside the outer try block, which ealls the method. Here, is the previous program recorded 50 that the nested try block is moved inside the method nestedtry () Example 2: class Method NestedTry { 49 4.3.6 THROW STATEMENT. JAVA PROGRAMMING (DIP. V SEM. CO,[Link]) static void nestedtry (int k) UW nestedtry block U1 division by zero int) = (1,2,3,4)5 t(10] = 25; UW generate an out-of-bounds exception } } catch (ArrayIndexOutOfBoundException e) { [Link] (“Array index out-of bound” +o); i } public static void main (String args []) { ty { inta=0; int b= 25/5 [Link] (“a= "+ a); nestedtry (a); } catch(ArithmeticException e) { z [Link] printIn (“Divided by 0” +c); 3 } } fens Qu. Explain the following clause with respect to © exception han ra z 6 throw. 809,13, W12 (IM), » /S:14, W-14 (2M), MSBTE-SOQP (2M) DJ- Text Book Series 410 There may be times when we would like to throw ur own exceptions. We can do this by using the keyword throw as follows : throw new Throwable 'e subclass; For example, throw new ArithmeticException (); throw new NumberFormatException (); The following example demonstrates the use of a user-defined subclass of throwable class. Note that exception is a subclass of throwable and therefore My Exception is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught. Example: import [Link]. Exception; class MyException extends Exception { MyException (String message) { super (message); 3 } class TestMyExeeption { Public static void main (String args{]) { 5, y= 1000; if (2<0.01) { throw new MyException (“Number is small” } a3 catch(MyEXception e) Tc [Link] (“caught my Exception” 3 a catch (MyException e) AVA PROGRAMMING (DIP. SEM oo [Link] (“Caught My exceprig,~* [Link] ([Link] () ), } finally, { } 3 } (Output : Caught my exception ‘Number is [Link] Lam always here [Link]* Tam always here * The object e which contains the error message “Number is too small” is caught by the catcj block which then displays the message using the getMessage () method. Program 1: Write a program to throw a user defined exception as “invalid age” if age entered user is less than eighteen, Reza ‘Ans. class AgeException extends Exception { String s; AgeException (String ss) { } String tostring () return s; } } Public class Example | { public static void main (String args f)) { scanner input = new scanner (System. in); int age; [Link] printin“Enter an Age : »; age=[Link] (); ” try { — wa ook Series (oir. v SEM, [Link]) oge0;4-— { [Link] printin (“Child Thread :”+ i); Thread . sleep(500) ; sh Interrupted Exception e) system out pritIn(*Child intereupted» sem [Link](“ENiting child thread") jass Extend Thread { ae puble static void main (String args () { new NewThread (); //create a new thread wy { for (int i { system [Link](“Main Thread :" +i); Thread sleep(1000) ; } } catch (Interrupted Exception ¢) { [Link](“Main thread interrupted.”) ; } [Link](“Main thread exiting.”) } } This program generates thi preceding version. As we can see, is created by _instantiating New Thread, which is derived from thread. Notice the call to super ( ) inside New Thread This invokes the following form of the Thread 1e same output as the the child thread an object of constructor : public Thread (Stringthread Name) Here, thread Name specifies th of the thread, e name Preceding examples, this i 1g sleep () within main ( » delay to ensure that all child 1 Prior to the main thread. r7_sava procrammin (O1P.v SEM. [Link]) * However, this is hardly a satisfactory solution, and it also raises a larger question : How ean one thread know when another thread has ended? Fortunately, Thread provides a means by which We can answer this question. Two ways exist 10 determine whether a thread has finished. ‘© First, we ean call isAlive () on the thread. This method is defined by Thread, and its general form is shown here final boolean isAlive () ‘© The isAlive (.) method returns true if the thread ‘upon which it is called is still running. It returns false otherwise. © While isAlive () is occasionally useful, the method that we will more commonly use to wait for a thread to finish is called join (), shown here: final void join () throws InterruptedException. ‘© This method waits until the thread on which itis called terminates, Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join () allow us to specify a maximum amount of time that we want to wait for the specified thread to terminate. Here is an improved version of the preceding example that uses join ( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive () method. Example Using join () to wait for threads to finish. class New Thread implements runnable { string name :// name of thread ‘Thread t NewThread (String threadname) { name = threadname ; t= new Thread (this, name) ; [Link]("New thread :"+) 5 tstart( ); “Start the thread } W This is th public void run () 1e entry point for thread. DJ- Text Book Series “0 —— 7 = Sample output from this program js \ vary based on proce try { (our output may ae p for (inti=5;i>0;i--y 4 Speed and task load.) [Link] (name +: + i); Output: Thread sleep(1000) ; } } catch (InterruptedExcept [Link](name + } System out printin(name + exiting.”) ; , 3 class DemoJoin { Public static void main (String args []) { NewThread ob] = new NewThread (“One” NewThread ob2 = new NewThread (“Two” NewThread ob3 = new NewThread (“Three”) ; [Link](“"Thread One is alive :"-+ obl.t. [Link](“Thread Two is al ob2.t. isAlive ()); ‘[Link](*“Thread Three is alive : "+ 0b 3.t. isAlive ( )) // wait for threads to finish wry { ‘[Link](“Waiting for threads to finish.”); [Link](); [Link](); [Link] (); } catch (InterruptedException e) { ‘[Link](“Main thread interrupted.” ; } [Link](“Thread One is alive :” + obl.t. isAlive ()) ; [Link](““Thread Two is alive :”-+ ob2.t. isAlive ()); [Link] printIn(“Thread Three is alive :” + 0b3.t. isAlive ()) ‘[Link](“Main thread exiting.”) ; } } New thread . Thread [One, 5, main} New thread . Thread (Two, 5, main} New thread . Thread (Three, 5, main] Thread One is alive : true Thread Two is alive : true Thread Three is Waiting for threads to finish, true One : 5 Two:5 Three: 5 One: 4 Two:4 Three: 4 One : 3 Two :3 Three :3 One : 2 Two :2 Three : 2 Two exiting, Three exiting, One exiting, Thread One is alive : false Thread Two is alive : false Thread Three is aliv Main thread exiting, : false ———_ AS we can see, afer the calls to join (), tu threads have stopped executing p y 2 er CLE OF TREAD : — ‘san peseribe the complete life cycle of 7 Vy ‘Yele of threads, 1W-08,10,14 (4M), W116, 8-14 (any 12 Fxplain Tife cycle of thread a je! disgram. along with] 5-09, W-09,13 (4M), S-11, W-12 (8M MSBTE-SOP (3M) 3. With suitable diagram explain the lite ad of thread. ‘8-13 (8M) During the life time of a thread, there are many states it can enter. They include. (1) Newborn state. @) Runnable state. (3) Running (4) Blocked state. (5) Dead state. A thread is always in one of these five states. It ‘can move from one state to another via a variety Fig.4.6.(a). Nun- Rennable der miinote do: of ways shown New thread Newborn [= CD Active thread Conn) Killed thread suspend resume sleep wait notify ‘sop Idle thread (Not Runnable) ofa thread Fig. 46 (a) State transition diagra™ () Newborn state : * When we create a thread objec! to be in newborn state. 4, the thread is born at Relinguish - ore er, wert. 1p. V SEM. CO.C! LAVA PROGRAMMING (0! led for running, At of the following The thread is not yet schedu this state, we can do only one things with it (i Schedule it for running using start ( ) method. (ii) Kill it using stop () method. If scheduled, it moves to the runnable state. Fig.4.6(b). If we attempt to use any other method at this stage, an exception will be thrown Fig. 4.6 (b) Scheduling a newborn thread Runnable state + The runnable state means that the thread is ready for execution and is waiting for the availablity of the processor. ‘That is, the thread has joined the queue of thread that are waiting for execution. If all threads have equal priority; then they are given slots for execution in round robin fashion, i.e. first come, first serve manner. The thread that relinquishes control joins the {queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing. — However, if-we want a thread to relinquish control to another thread to equal priority before its turn comes, we can do so by using the yield () method. eld © Running Runnable threads thread {) Relinquishing control using yield{) method. Fig.

You might also like