Iot Oops Chap 3
Iot Oops Chap 3
Iot Oops Chap 3
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
4) Scenario where
ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following
tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
Java finally block
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but
only one finally block.
Note: The finally block will not be executed if program exits(either by
calling System.exit() or by causing a fatal error that causes the
process to abort).
Multiple catch()
1. public class multipleCatch {
2.
3. public static void main(String[] args) {
4.
5. try {
6. int list[] = new int[5];
7. list[2] = 10;
8. list[4] = 2;
9. list[10] = list[2] / list[4];
10. }
11. catch(ArithmeticException ae) {
12. System.out.println("Problem info: Value of divisor can not
be ZERO.");
13. }
14. catch(ArrayIndexOutOfBoundsException aie) {
15. System.out.println("Probleminfo:
ArrayIndexOutOfBoundsException has occured.");
16. }
17. catch(Exception e) {
18. System.out.println("Problem info: Unknown exception has
occured.");
19. }
20. }
21. }
Throw
import java.util.Scanner;
public class throwExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not
posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}
Throws
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
System.out.println(e.toString());
System.out.println("\n rest of the code12...\n");
e.printStackTrace();
System.out.println("\n rest of the code34...\n");
System.out.println(e.getMessage());
}
System.out.println("\n rest of the code56...\n");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code12...
java.lang.ArithmeticException: / by zero
at MultipleCatchBlock5.main(MultipleCatchBlock5.java:5)
rest of the code34...
/ by zero
rest of the code56...
try{
try{
String name="Fasi";
int b = Integer.parseInt(name);
System.out.println(b);
}catch(Exception e)
{
System.out.println(e);
}
System.out.println("\trest of the code111");
Output:
java.lang.ArithmeticException: not validat TestThrow1.validate(TestThrow1.java:4)
at TestThrow1.main(TestThrow1.java:10)
rest of the code...
t1.division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}}
Example for User defined exception
import java.util.Scanner;
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
As you can see in the above program that there is no context-switching because here t1 and t2 will
be treated as normal object not thread object.
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
Example of join(long miliseconds) method
1. class TestJoinMethod2 extends Thread{
2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. TestJoinMethod2 t1=new TestJoinMethod2();
12. TestJoinMethod2 t2=new TestJoinMethod2();
13. TestJoinMethod2 t3=new TestJoinMethod2();
14. t1.start();
15. try{
16. t1.join(1500);
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }
Test it Now
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and
t3 starts executing.
getName(),setName(String) and getId() method:
public String getName()
next →← prev
Current Thread
The currentThread() method returns a reference of currently executing thread.
1. public static Thread currentThread()
Example of currentThread() method
1. class TestMultiNaming2 extends Thread{
2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. public static void main(String args[]){
6. TestMultiNaming2 t1=new TestMultiNaming2();
7. TestMultiNaming2 t2=new TestMultiNaming2();
8.
9. t1.start();
10. t2.start();
11. }
12. }
Test it Now
Output:Thread-0
Thread-1
JVM wait until user threads to finish their The JVM will’t wait for daemon threads to finish
work. It never exit until all user threads finish their work. The JVM will exit as soon as all user
their work. threads finish their work.
User threads are created by the application. Mostly Daemon threads created by the JVM.
Mainly user threads are designed to do some Daemon threads are design as to support the
specific task. user threads.
User threads are foreground threads. Daemon threads are background threads.
User threads are high priority threads. Daemon threads are low priority threads.
1) public void setDaemon(boolean is used to mark the current thread as daemon thread or user
status) thread.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such a way,
we can suspend, resume or interrupt a group of threads by a single method call.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other
thread group. The thread group creates a tree in which every thread group except the
initial thread group has a parent.
A thread is allowed to access information about its own thread group, but it cannot access
the information about its thread group's parent thread group or any other thread groups.
2) ThreadGroup(ThreadGroup parent, String name) creates a thread group with a given parent group and name.
1) void checkAccess() This method determines if the currently running thread has
permission to modify the thread group.
2) int activeCount() This method returns an estimate of the number of active threads in
the thread group and its subgroups.
3) int activeGroupCount() This method returns an estimate of the number of active groups in
the thread group and its subgroups.
4) void destroy() This method destroys the thread group and all of its subgroups.
5) int enumerate(Thread[] list) This method copies into the specified array every active thread in the
thread group and its subgroups.
6) int getMaxPriority() This method returns the maximum priority of the thread group.
7) String getName() This method returns the name of the thread group.
8) ThreadGroup getParent() This method returns the parent of the thread group.
9) void interrupt() This method interrupts all threads in the thread group.
10) boolean isDaemon() This method tests if the thread group is a daemon thread group.
11) void setDaemon(boolean This method changes the daemon status of the thread group.
daemon)
12) boolean isDestroyed() This method tests if this thread group has been destroyed.
13) void list() This method prints information about the thread group to the
standard output.
14) boolean parentOf(ThreadGroup g This method tests if the thread group is either the thread group
argument or one of its ancestor thread groups.
15) void suspend() This method is used to suspend all threads in the thread group.
16) void resume() This method is used to resume all threads in the thread group which
was suspended using suspend() method.
17) void setMaxPriority(int pri) This method sets the maximum priority of the group.
18) void stop() This method is used to stop all threads in the thread group.
19) String toString() This method returns a string representation of the Thread group.