Skip to main content
Open navigation menu
Close suggestions
Search
Search
en
Change Language, English
Upload
Sign in
Sign in
0 ratings
0% found this document useful (0 votes)
15 views
47 pages
Java CHP 4 Notes
Uploaded by
Pandurang k Kamble
AI-enhanced title
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
Download
Save
Save Java Chp 4 Notes For Later
Share
0%
0% found this document useful, Mark this document as useful
0%
0% found this document not useful, Mark this document as not useful
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
15 views
47 pages
Java CHP 4 Notes
Uploaded by
Pandurang k Kamble
AI-enhanced title
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
Go to previous items
Download
Save
Save Java Chp 4 Notes For Later
Share
0%
0% found this document useful, Mark this document as useful
0%
0% found this document not useful, Mark this document as not useful
Print
Embed
Report
Go to next items
Download
Save Java Chp 4 Notes For Later
Share
More options
Fullscreen
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 } } eep- 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]) oge
java RunThread. Thread started Thread (Runnable object, String name) Thread (Thread Group group, Runnable object) Thread ( Thread Group group, StringName) Following table shows the methods to create a Thread (Thread Group group, Runnable object, thread class : String name) Fr Methods Description _| + For creating a thread we have to follow the | [eurrentThread () Rena mises te following steps currently executing (i) Extend the java . lang . Thread class. _. Thread. (ii) Override the run (.) method in the subclass from me N ae Returns thread priority the thread class to define the code executed by the interrupe(} Pbtains a thread name al interrupts the current (iii) Create an instance of this subclass. This subclass | | is Daemon () a eee may call a thread class constructor by subclass stein teaetete constructor. false, __J Invoke - 3167, AE oext Book Series ait) 's Aliveretum wus thread has been started and has not yet dead else false, gia done miliscconds) Wait for a thread to terminate, Di Entry point of thread. It implement Runnable interface Sets prority of thread . Suspends thread for a Period of time, 0;i--) ( [Link] (“Child Thread: ” +i); Thread . sleep(500) ; } } catch (InterruptedException e) i [Link](“Child interrupted. ) System out printin( “Exiting child thread”) ; ) ) class ThreadDemoDJ Text Book Series ‘ args 11) { Dublie static void main (String newThread () ; Hereate a new thread ty { for (int Ssi>0;i--+¢ [Link](“Main Thread : “+ i); Thread .sleep(1000) ; } } catch (InterruptedException e) { [Link], PrintIn(“Main thread interrupted.”) ; } [Link]¢*Main thread exiting.”); } } Inside New Thread's constructor, a new thread object is created by the following statement : t= newThread (this, “DemoThread”) Passing this as the first argument indicates that we want the new thread to call the run () method on this object, Next, start () is called, which starts the thread of execution beginning at the run () method. This causes the child thread’s for loop to begin. After calling start ( ) , NewThread’s constructor returns to main( ). When the main thread Tesumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish The output produced by this program is as follows. (our output may vary based on processor speed and task load) ‘Output: Child thread : Thread [Demo thread , 5, main ] Main Thread : 5 Child Thread : 5 Child Thread : 4 Main Thread : 4 Child Thread : 3 Child Thread : 2 420 JAVA PROGRAMING (IP. 514 o Child Thread : 1 Exiting child thread Main Thread : 2 1 Main Thr Main Thread © Tn a multithreaded program, offen the mai must be the last thread to finish running. 4, Py for some older JVMs, if the main thread f, before a child thread has completed, then run-time system may “hang”. The preceding program ensures that the ma. thread finishes last, because the main tj sleeps for 1,000 milliseconds between itera, but the child thread sleeps. for only sy milliseconds, This causes the child thea, terminate earlier than the main thread, Mish he ayy D CLASS XTENDING THE THE The second way to create a thread is to create» new class that extends Thread, and then to cri an instance of that class. The extending cles must override the run () method, which isthe entry point for the new thread. It must also call start () to begin execution of the new thread. Here is the preceding program rewritten to extend Thread : W Create a second thread by extending thread Class New Thread extends Thread { ‘New thread () { 4 Create a new, second thread super(“Demo thread”) ; [Link] printin (“Child thread :" + this); start ();/start the thread } 1 This is the entry point for the second thread. public void run () ty for (inti= 5 51>0;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 py 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
Types of Errors in Java Programming
PDF
No ratings yet
Types of Errors in Java Programming
42 pages
Exception and File Handling Basics
PDF
No ratings yet
Exception and File Handling Basics
37 pages
Managing Errors and Exceptions
PDF
No ratings yet
Managing Errors and Exceptions
27 pages
Java Error and Exception Management Guide
PDF
No ratings yet
Java Error and Exception Management Guide
38 pages
Exception Handling
PDF
No ratings yet
Exception Handling
10 pages
Java Exception Handling Basics
PDF
100% (1)
Java Exception Handling Basics
61 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
32 pages
Java Exception and Error Handling Guide
PDF
No ratings yet
Java Exception and Error Handling Guide
33 pages
Java Error Handling and Exceptions
PDF
No ratings yet
Java Error Handling and Exceptions
66 pages
JP Unit 4
PDF
No ratings yet
JP Unit 4
83 pages
Java Exception Handling and Multithreading
PDF
No ratings yet
Java Exception Handling and Multithreading
83 pages
Object Oriented Programming With Java-Unit-II
PDF
No ratings yet
Object Oriented Programming With Java-Unit-II
57 pages
Exception Handling in Java Programming
PDF
No ratings yet
Exception Handling in Java Programming
33 pages
Exception Handling in JavaException Handling in Java
PDF
No ratings yet
Exception Handling in JavaException Handling in Java
56 pages
Exception Handling
PDF
No ratings yet
Exception Handling
34 pages
Java Multithreading Execution Order
PDF
No ratings yet
Java Multithreading Execution Order
26 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
64 pages
Managing Java Errors and Exceptions
PDF
No ratings yet
Managing Java Errors and Exceptions
169 pages
Java Exception Handling Basics
PDF
No ratings yet
Java Exception Handling Basics
27 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
73 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
27 pages
Runtime Error Handling in Java
PDF
No ratings yet
Runtime Error Handling in Java
5 pages
Java Exception Handling Concepts
PDF
No ratings yet
Java Exception Handling Concepts
37 pages
Exception Handling in Java Programming
PDF
No ratings yet
Exception Handling in Java Programming
29 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
40 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
63 pages
Unit No-3
PDF
No ratings yet
Unit No-3
28 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
23 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
42 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
32 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
62 pages
Java Exception Handling Guide
PDF
No ratings yet
Java Exception Handling Guide
19 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
10 pages
Java Exception Handling & Multithreading
PDF
No ratings yet
Java Exception Handling & Multithreading
75 pages
Java Exception Handling Techniques
PDF
No ratings yet
Java Exception Handling Techniques
27 pages
Java Exception Handling Guide
PDF
No ratings yet
Java Exception Handling Guide
19 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
29 pages
Scan Document2026-03-06 17-48-39
PDF
No ratings yet
Scan Document2026-03-06 17-48-39
26 pages
Managing Java Errors and Exceptions
PDF
No ratings yet
Managing Java Errors and Exceptions
27 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
31 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
10 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
20 pages
Java Exception Handling Basics
PDF
No ratings yet
Java Exception Handling Basics
43 pages
Java Exception Handling Basics
PDF
No ratings yet
Java Exception Handling Basics
24 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
28 pages
06 Exceptions
PDF
No ratings yet
06 Exceptions
25 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
15 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
28 pages
Types of Errors and Exceptions in Java
PDF
No ratings yet
Types of Errors and Exceptions in Java
7 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
41 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
42 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
20 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
19 pages
Understanding Java Exceptions and Handling
PDF
No ratings yet
Understanding Java Exceptions and Handling
75 pages
Java Chapter 5
PDF
No ratings yet
Java Chapter 5
107 pages
ExceptionHandling Java Notes InterviewQA
PDF
No ratings yet
ExceptionHandling Java Notes InterviewQA
10 pages
Java Exception Handling Explained
PDF
No ratings yet
Java Exception Handling Explained
41 pages
Java Exception Handling Overview
PDF
No ratings yet
Java Exception Handling Overview
41 pages