Unit 5 - Exception Handling & Multithreaded

Similar documents
Software Practice 1 - Multithreading

By: Abhishek Khare (SVIM - INDORE M.P)

Unit III Rupali Sherekar 2017

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

JAVA - MULTITHREADING

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Module - 4 Multi-Threaded Programming

Here is a hierarchy of classes to deal with Input and Output streams.

04-Java Multithreading

CSC 1214: Object-Oriented Programming

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

7. MULTITHREDED PROGRAMMING

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Unit - IV Multi-Threading

BBM 102 Introduction to Programming II Spring Exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

JAVA. Lab 12 & 13: Multithreading

BBM 102 Introduction to Programming II Spring 2017

Fundamentals of Object Oriented Programming

Multithreaded Programming

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming

Concurrent Programming using Threads

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Exception Handling in Java


CIS233J Java Programming II. Threads

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

ECE 122. Engineering Problem Solving with Java

C16b: Exception Handling


Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Chapter 13 Exception Handling

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Object Oriented Programming (II-Year CSE II-Sem-R09)

17. Handling Runtime Problems

Programming II (CS300)

Amity School of Engineering

6.Introducing Classes 9. Exceptions

More on Exception Handling

Object Oriented Programming. Week 10 Part 1 Threads

Chapter 12 Exception Handling

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Java Errors and Exceptions. Because Murphy s Law never fails

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

More on Exception Handling

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

UNIT V CONCURRENT PROGRAMMING

Std 12 Lesson-10 Exception Handling in Java ( 1

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Exceptions - Example. Exceptions - Example

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

Programming II (CS300)

Contents. 6-1 Copyright (c) N. Afshartous

National University. Faculty of Computer Since and Technology Object Oriented Programming

CMSC 132: Object-Oriented Programming II. Threads in Java

Java Threads. COMP 585 Noteset #2 1

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Chapter 14. Exception Handling and Event Handling ISBN

Download link: Java Exception Handling

Object-Oriented Programming Concepts-15CS45

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Exception Handling. --After creating exception object,method handover that object to the JVM.

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Object Oriented Programming Exception Handling

Java Programming Language Mr.Rungrote Phonkam

What are Exceptions?

Multithread Computing

Program Correctness and Efficiency. Chapter 2

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Data Structures. 02 Exception Handling

Programming Java. Multithreaded Programming

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

15CS45 : OBJECT ORIENTED CONCEPTS

Multi-threading in Java. Jeff HUANG

CS 556 Distributed Systems

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Multithreading Pearson Education, Inc. All rights reserved.

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

CSCI 261 Computer Science II

Object Oriented Programming

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Animation Part 2: MoveableShape interface & Multithreading

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

CSC207H: Software Design. Exceptions. CSC207 Winter 2018


About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Transcription:

Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application terminates abnormally, therefore these exceptions are needs to be handled. A Java Exception is an object that describes the exception that occurs in a program. When an exceptional event occurs in java, an exception is said to be thrown. An exception can occur for many different reasons, some of them are as given below: o A user has entered invalid data. o A file that needs to be opened cannot be found. o A network connection has been lost in the middle of communications, or the JVM has run out of memory. Exceptions are caused by users, programmers or when some physical resources get failed. The Exception Handling in java is one of the powerful mechanisms to handle the exception (runtime errors), so that normal flow of the application can be maintained. In Java there are three categories of Exceptions: 1) Checked exceptions: A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. Example, IOException, SQLException etc. 2) Runtime exceptions: An Unchecked exception is an exception that occurs during the execution, these are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. 3) Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. OutOfMemoryError, VirtualMachineErrorException. All exception classes are subtypes of the java.lang.exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. 1 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. JVM is out of Memory. Normally programs cannot recover from errors. The Exception class has two main subclasses: IOException class and RuntimeException class. Exception Handling Mechanism Exception handling is done using five keywords: 1) 2) catch 3) finally 4) throw 5) throws Using and catch 1) block : o Java block is used to enclose the code that might throw an exception. It must be used within the method. o Java block must be followed by either catch or finally block. 2) catch block: o Java catch block is used to handle the Exception. It must be used after the block only. o The catch block that follows the is checked, if the type of exception that occurred is listed in the catch block then the exception is handed over to the catch block that handles it. o You can use multiple catch block with a single. Syntax: //Protected code catch(exceptionname1 e1) //Catch block 1 catch(exceptionname2 e2) //Catch block 2 o In above syntax, there are two catch blocks. In block, we write code that might generate exception. If the exception generated by protected code then exception thrown to the first catch block. o If the data type of the exception thrown matches ExceptionName1, it gets caught there and execute the catch block. o If not, the exception passes down to the second catch block. o This continues until the exception either is caught or falls through all catches, in that case the current method stops execution. 2 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

class demotry public static void main(string[] args) int arr[]=1,2,3; arr[3]=3/0; catch(arithmeticexception ae) System.out.println("Divide by zero :: " + ae); catch(arrayindexoutofboundsexception e) System.out.println("Array index out of bound exception :: "+e); divide by zero :: java.lang.arithmeticexception: / by zero Nested Try-Catch Blocks o In java, the block within a block is known as nested block. o Nested block is used when a part of a block may cause one error while entire block may cause another error. o In that case, if inner block does not have a catch handler for a particular exception then the outer is checked for match. o This continues until one of the catch statements succeeds, or until the entire nested statements are done in. If no one catch statements match, then the Java run-time system will handle the exception. Syntax: Statement 1; //Protected code catch(exceptionname e1) //Catch block1 catch(exceptionname1 e2) 3 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

//Catch block 2 class demotry1 public static void main(string[] args) int arr[]=5,0,1,2; arr[4] = arr[3]/arr[1]; catch(arithmeticexception e) System.out.println("divide by zero :: "+e); catch(arrayindexoutofboundsexception e) System.out.println("array index out of bound exception :: "+e); catch(exception e) System.out.println("Generic exception :: "+e); System.out.println("Out of..catch block"); divide by zero :: java.lang.arithmeticexception: / by zero Out of..catch block 3) finally: o A finally keyword is used to create a block of code that follows a or catch block. o A finally block of code always executes whether or not exception has occurred. o A finally block appears at the end of catch block. Syntax: //Protected code catch(exceptiontype1 e1) //Catch block 1 4 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

catch(exceptiontype2 e2) //Catch block 2 finally //The finally block always executes. class demofinally public static void main(string args[]) int a[] = new int[2]; System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); finally a[0] = 10; System.out.println("First element value: " +a[0]); System.out.println("The finally block is always executed"); System.out.println("Out of...catch...finally... "); Exception thrown :java.lang.arrayindexoutofboundsexception: 3 First element value: 10 The finally block is always executed Out of...catch...finally... Key points to keep in mind: o A catch clause cannot exist without a statement. o It is not compulsory to have finally clause for every /catch. o The block cannot be present without either catch clause or finally clause. o Any code cannot be present in between the, catch, finally blocks. 5 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

4) throw : o The throw keyword is used to explicitly throw an exception. o We can throw either checked or uncheked exception using throw keyword. o Only object of Throwable class or its sub classes can be thrown. o Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax: throw ThrowableInstance; class demothrow static void demo() throw new ArithmeticException("demo"); catch(arithmeticexception e) System.out.println("Exception caught"); public static void main(string args[]) demo(); Exception caught 5) throws: o The throws keyword is used to declare an exception. o If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. o You can declare multiple exceptions. Syntax: return_type method_name() throws exception_class_name_list //method code class demothrows static void display() throws ArithmeticException System.out.println("Inside check function"); 6 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

throw new ArithmeticException("Demo"); public static void main(string args[]) display(); catch(arithmeticexception e) System.out.println("caught :: " + e); Inside check function caught :: java.lang.arithmeticexception: Demo User Defined Exception In java, we can create our own exception that is known as custom exception or user-defined exception. We can have our own exception and message. Key points to keep in mind: o All exceptions must be a child of Throwable. o If you want to write a checked exception that is automatically enforced by the Declare Rule, you need to extend the Exception class. o If you want to write a runtime exception, you need to extend the RuntimeException class. class demouserexception extends Exception private int ex; demouserexception(int a) ex=a; public String tostring() return "MyException[" + ex +"] is less than zero"; class demoexception static void sum(int a,int b) throws demouserexception if(a<0) 7 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

else throw new demouserexception (a); System.out.println(a+b); public static void main(string[] args) sum(-10, 10); catch(demouserexception e) System.out.println(e); MyException[-10] is less than zero List of Java Exception (Built-In Exception) Java defines several built-in exception classes inside the standard package java.lang. Checked Exception: Exception ClassNotFoundException IllegalAccessException NotSuchMethodException NoSuchFieldException Description This Exception occurs when Java run-time system fail to find the specified class mentioned in the program. This Exception occurs when you create an object of an abstract class and interface. This Exception occurs when the method you call does not exist in class. A requested field does not exist. Unchecked Exception: Exception ArithmeticException ArrayIndexOutOfBounds Exception NumberFormatException Description This Exception occurs, when you divide a number by zero causes an Arithmetic Exception. This Exception occurs, when you assign an array which is not compatible with the data type of that array. This Exception occurs, when you to convert a string variable in an incorrect format to integer (numeric format) that is not 8 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

ClassCastException NullPointerException compatible with each other. Invalid cast. Invalid use of a null reference. Multithreading Java is a multithreaded programming language which means we can develop multi threaded program using Java. Multithreaded programs contain two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area which saves memory, and context-switching between the threads takes less time than process. Threads are independent. So, it doesn't affect other threads if exception occurs in a single thread. Java Multithreading is mostly used in games, animation etc. For example, one thread is writing content on a file at the same time another thread is performing spelling check. In Multiprocessing, Each process has its own address in memory. So, each process allocates separate memory area. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. So that cost of communication between the processes is high. Disadvantage: If you create too many threads, you can actually degrade the performance of your program rather than enhance it. Remember, some overhead is associated with context switching. If you create too many threads, more CPU time will be spent changing contexts than executing your program. Life Cycle of Thread A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Diagram: 9 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

New: o A new thread begins its life cycle in the New state. It remains in this state until the program starts the thread by invoking Start() method. It is also referred to as a born thread. Runnable: o The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. o The thread is in running state if the thread scheduler has selected it. Waiting: o Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed waiting: o A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transition back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated: o A runnable thread enters the terminated state when it (run() method exits) completes its task. Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. Creating a Thread Thread class provide constructors and methods to create and perform operations on a thread. 1) Constructor of Thread class: Thread () Thread (String name) Thread (Runnable r) Thread (Runnable r, String name) 2) Methods of Thread Class: Method public void run() public void start() public String getname() public void setname(string name) Description En point for a thread Start a thread by calling run() method. Return thread's name. To give thread a name. 10 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

public int getpriority() public int setpriority(int priority) public final boolean isalive() public static void sleep(long millisec) public final void join(long millisec) Return thread's priority. Sets the priority of this Thread object. The possible values are between 1 and 10. Checks whether thread is still running or not. Suspend thread for a specified time. Wait for a thread to end. Java defines two ways by which a thread can be created. o By implementing the Runnable interface. o By extending the Thread class. 1) By implementing the Runnable interface: The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface, the class needs to implement the run() method, which has following form: public void run( ) This method provides en point for the thread and you will put you complete business logic inside this method. After that, you will instantiate a Thread object using the following constructor: Thread (Runnable threadobj, String threadname) ; Where, threadobj is an instance of a class that implements the Runnable interface and threadname is the name given to the new thread. Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. void start ( ); class demothread3 implements Runnable public void run() System.out.println("Thread is running..."); public static void main(string args[]) demothread3 d1=new demothread3 (); Thread t1 =new Thread(d1); t1.start(); Thread is running... 11 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

class RunnableDemo implements Runnable Thread t; String threadname; RunnableDemo( String name) threadname = name; System.out.println("Creating " + threadname ); public void run() System.out.println("Running " + threadname ); for(int i = 2; i >= 0; i--) System.out.println("Thread: " + threadname + ", " + i); // Let the thread sleep for a while. Thread.sleep(1000); catch (InterruptedException e) System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () System.out.println("Starting " + threadname ); if (t == null) t = new Thread (this, threadname); t.start (); public class ThreadDemo public static void main(string args[]) RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); 12 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Creating Thread-1 Starting Thread-1 Running Thread-1 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, 0 Thread Thread-1 exiting. 2) By extending the Thread class. Second way to create a thread is to create a new class that extends Thread class and then create an instance of that class. The extending class must override the run( ) method, which is the en point for the new thread. Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. class demothread2 extends Thread public void run() System.out.println("Thread is running..."); public static void main(string args[]) demothread2 t1 = new demothread2(); t1.start(); Thread is running... class ThreadDemo extends Thread Thread t; String threadname; ThreadDemo( String name) threadname = name; System.out.println("Creating " + threadname ); public void run() 13 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

System.out.println("Running " + threadname ); for(int i = 2; i >= 0; i--) System.out.println("Thread: " + threadname + ", " + i); // Let the thread sleep for a while. Thread.sleep(1000); catch (InterruptedException e) System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () System.out.println("Starting " + threadname ); if (t == null) t = new Thread (this, threadname); t.start (); public class ThreadDemo2 public static void main(string args[]) ThreadDemo T1 = new ThreadDemo( "Thread-1"); T1.start(); Creating Thread-1 Starting Thread-1 Running Thread-1 Thread: Thread-1, 2 Thread: Thread-1, 1 14 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Thread: Thread-1, 0 Thread Thread-1 exiting. Thread Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this synchronization achieved is called thread synchronization. The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock. Syntax: synchronized(object) // statements to be synchronized o Here, object is a reference to the object being synchronized. o A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object's critical section. class PrintDemo public void printcount() for(int i = 3; i > 0; i--) System.out.println("Counter --- " + i ); catch (Exception e) System.out.println("Thread interrupted."); class ThreadDemo extends Thread Thread t; String threadname; PrintDemo PD; ThreadDemo( String name, PrintDemo pd) threadname = name; 15 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

PD = pd; public void run() synchronized(pd) PD.printCount(); System.out.println("Thread " + threadname + " exiting."); public void start () System.out.println("Starting " + threadname ); if (t == null) t = new Thread (this, threadname); t.start (); public class ThreadSchro public static void main(string args[]) PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); Starting Thread - 1 Starting Thread - 2 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 1 exiting. Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting. 16 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Inter-thread Communication Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Inter-thread communication is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. To avoid polling(it is usually implemented by loop), Inter-thread communication is implemented by following methods of Object class: o wait( ): This method tells the calling thread to give up the critical section and go to sleep until some other thread enters the same critical section and calls notify( ). o notify( ): This method wakes up the first thread that called wait( ) on the same object. o notifyall( ): This method wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. Above all methods are implemented as final in Object class. All three methods can be called only from within a synchronized context. class Customer int amount=10000; synchronized void withdraw(int amount) System.out.println("going to withdraw..."); if(this.amount<amount) System.out.println("Less balance; waiting for deposit..."); wait(); catch(exception e) this.amount-=amount; System.out.println("withdraw completed..."); synchronized void deposit(int amount) System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); class InterThreadDemo public static void main(string args[]) 17 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

final Customer c = new Customer(); new Thread() public void run()c.withdraw(15000);.start(); new Thread() public void run()c.deposit(10000);.start(); going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed... 18 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana