0% found this document useful (0 votes)
54 views20 pages

CC 41 C Exception&amp Threading

Java allows programs to utilize multithreading by dividing a program into multiple subprograms called threads that can run concurrently. There are two main ways to create threads in Java - by extending the Thread class and overriding its run() method, or by implementing the Runnable interface and overriding its run() method. The run() method defines the set of instructions that will be executed by the thread. Multithreading allows a program to perform multiple tasks simultaneously but introduces complexity in ensuring thread-safety and debugging concurrent programs.

Uploaded by

prynka06
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views20 pages

CC 41 C Exception&amp Threading

Java allows programs to utilize multithreading by dividing a program into multiple subprograms called threads that can run concurrently. There are two main ways to create threads in Java - by extending the Thread class and overriding its run() method, or by implementing the Runnable interface and overriding its run() method. The run() method defines the set of instructions that will be executed by the thread. Multithreading allows a program to perform multiple tasks simultaneously but introduces complexity in ensuring thread-safety and debugging concurrent programs.

Uploaded by

prynka06
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Exceptional Handling

An exception in Java is a signal that indicates the occurrence of some important or unexpected condition during execution. For example: A requested file cannot be found An array index is out of bounds A network link failed. Java provides an exception handling mechanism for systematically dealing with such error conditions. A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.

Java exception handling keywords


try-To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. catch-Immediately following the try block, include a catch block that specifies the exception type that you wish to catch throw-So far we have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly , using the throw statement throws-A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. finally- It 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.

Types of exceptions

Error Throwable Exception IOException Runtime Exception

Using try and catch


class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e){ // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); }}

Javas Built-in Exceptions


Inside the standard package java.lang, Java defines several exception classes. The most general of these exceptions are subclasses of the standard type RuntimeException. java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. These are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The exceptions defined by java.lang that must be included in a methods throws list if that method can generate exceptions and does not handle it itself they are called checked exceptions.

Some Runtime Exceptions


(These exceptions are not checked by java if try catch blocks are not defined)

Sr.no. 1. 2. 3. 4. 5. 6.

Exception ArithmeticException ArrayIndexOutOfBounds Exception

Meaning Arithmetic error, such as divide-by-zero. Array index is out-of-bounds.

IllegalArgumentException Illegal argument used to invoke a method. NegativeArraySizeExcept Array created with a negative size. ion NullPointerException Invalid use of a null reference. IllegalThreadStateExcepti Requested operation not compatible on with current thread state.

7.

IndexOutOfBoundsExcep Some type of index is out-of-bounds. tion

User defined exceptions


Although Javas built-in exceptions handle most common errors. We will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do:
Just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses dont need to actually implement anything it is their existence in the type system that allows you to use them as exceptions.

A Small Example of user defined exception


Class myexception extends exception{ myexception (String msg){ super (msg); }} Class employee{ String name; int age , category; employee(String n, int a, int c){ name=n; age=a; if (c<1 || c>4){ myexception ex =new myexception (invalid category); throw ex; } Category=c; }}

Class test { Public static void main(String arg[]){ try{ employee e1=new employee(x,30,2); employee e2=new employee(y,40,4); } Catch (myexception e){ System.out.println(caught + e); }

Single-Threaded Development
Many programs written for class so far have been single-threaded. Thread has a beginning,a body and a end and execute commands sequentially The program begins,run through a sequence of execution and finally ends. At a given pt there is only one statement under execution.

.
WHAT IF V WANT DIFFERENT TASKS OF PROGRAM TO BE EXECUTED CONCURRENTLY

Multithreading
Answer: is java included concept of
multithreading. MULTITHREADING is conceptual programming paradigm where a program is divided into two or more subprograms,which can be implemented at the same time in parellel

Creating Thread in java


Java provides two ways to create a new thread.
Extend the Thread class (java.lang.Thread) Implement the Runnable interface (java.lang.Runnable)

Run method in thread


Creating threads in java is simple.Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread Public void run() { .. //statement for implementing .. thread }

Extending The Thread class


Declare the class as extending the thread class. Implement the run() method that is responsible for executing the sequence of code that the thread will execute. Create a thread object and call the start() method to initiate the thread execution

Example of using thread class


Class A extends Thread public void run() { for(int i=1;i<=3;i++) { Sop(from thread A: i=+i); } { Sop(Exit form A);}} output from thread A: i=1 from thread A: j=2 from thread B: j=1 from thread B: j=2 From thread A: i=3 Class B extends Thread { public void run() { for(int j=1;j<=3;j++) { Sop(from Thread B: j=+j); } Sop(Exit form B);}} Class threadtest{ public Static void main(String arg[]) { new A().start(); new B().start(); } from thread B: j=3

More about Thread.run()


Like main(), run() defines a starting point for the JVM. What happens when the run() method exits?
The thread ends.

Another method - Runnable


A thread can also be created by implementing the Runnable interface instead of extending the Thread class Declare the class as implementing Runnable interface. Implement the run() method. Create a thread by Defining an object that is instantiated from this runnable class as the target of the thread. Call the threads start() method to run the thread.

Starting a Runnable
Pass an object that implements Runnable to the constructor of a Thread object, then start the thread as before.
Threadtest fr = new Threadtest(); Thread X = new Thread(Threadtest); X.start();

Example of Runnable interface


Class X implements runnable public void run() { for(int i=1;i<=3;i++) { Sop(from Thread A: i=+i); } from thread B: j=1 { Sop(Exit form A);}} output from thread A: i=1 from thread A: i=2 from thread A: i=3

Class threadtest{ public Static void main(String arg[]) { X runnable = new X(); Thread th = new Thread(runnable); th.start(); } }

Multithreading Pros and Cons


Pro: Multiple threads run concurrently on the system
Multiple tasks can be handled at once. Processing can be done in the background so as not to interrupt the user.

Con: Multiple threads run concurrently on the system


No more guarantees as to what has already happened, what objects have been initialized yet, etc. Code now has to be thread-safe or synchronized Debugging becomes much harder.

You might also like