You are on page 1of 21

KHK JAVA Unit-4

Managing Errors and Exceptions


What is an Error? Explain types of errors?
Error:
It is common to make mistakes while developing as well as typing a program. A
mistake might lead to an error causing to program to produce unexpected results. An
error may produce an incorrect output or may terminate the execution of program
abruptly or even may cause the system to crash.
Types of errors:
There are basically three types of errors in java program:
 Compile time Errors
 Run-time Errors
 Logical Errors
Compile-time errors:
These errors are detected at the time of compilation that’s why these are called
compile time errors. These are syntactical errors found in the code, due to which a
program fails to compile. Whenever the compiler displays an error, it will not create
the ―.class‖ file. Most of the compile-time errors are due to typing mistakes. The most
common problems are:
 Missing semicolons.
 Mismatch of brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
Run-time errors:
The errors occurred during program execution I known as run-time errors. These
errors represent inefficiency of the computer system to execute (run) a particular
statement. Run-time errors are not detected by the java compiler. They are detected by
the JVM, only at runtime. Most 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.

Vasavi Degree College 1


(C) www.anuupdates.org
KHK JAVA Unit-4

Logical errors:
These errors represent the errors in logic of the program. The programmer might be
using wrong formula or the design of the program itself is wrong. Logical errors are
not detected by either by java compiler or JVM. By comparing the output of a
program with manually calculated results, a programmer can guess the presence of a
logical error.

What is an Exception? Write about exception handling?


Exception:
An exception is an abnormal condition that arises in a code sequence at runtime. In
other words, an exception is a run-time error. The process of catching the exception
objects and continues the program execution with remaining code is known as
exception handling. The exception handling mechanism performs the following tasks:
 Find the problem.
 Inform that an error has occurred (throw the exception).
 Receive the error information (catch the exception).
 Take corrective actions (handle the exceptions).
Advantages:
 Separating Error-Handling Code from "Regular" Code.
 Propagating Errors up the Call Stack.
 Grouping and Differentiating Error Types

Explain Exception handling Mechanism with an example?


or
Explain try-catch syntax with an example?

The exception handling code basically consists of two segments, one to detect errors
and to throw exceptions and the other to catch exceptions and to take appropriate
actions. Java exception handling is managed via five keywords:

Vasavi Degree College 2


(C) www.anuupdates.org
KHK JAVA Unit-4

 try
 catch
 throw
 throws
 finally
Java uses a keyword ―try‖ to preface a block of code that is likely to cause an error
condition and ―throw‖ an exception. A catch block defined by the keyword ―catch‖
catches the exception thrown by the try block and handles it appropriately. The
general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
// ... finally {
// block of code to be executed before try block ends
}
The try block can have one or more statements that could generate an exception. If
anyone statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch block that is placed next to the try block.
The catch is passed a single parameter which is reference to the Exception object. If
the catch parameter matches with the type of exception object, then the exception
caught and statements in the catch block will executed.
Example:
class excep{
public static void main(String args[ ]){
try
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int r=x/y;
System.out.println(" x= "+x);

Vasavi Degree College 3


(C) www.anuupdates.org
KHK JAVA Unit-4

System.out.println(" y= "+y);
System.out.println(" r= "+r);
}
catch (Exception e) {
e.printStackTrace( );
}
System.out.println ("out of try catch block");
}
}
Output:
>javac excep.java
>java ex2 10 2 //first run with y value 2
x= 10
y= 2
r= 5
out of try catch block

>java ex2 10 0 // second run with y value 0


java.lang.ArithmeticException: / by zero
at ex2.main(ex2.java:6)
out of try catch block

Explain Exception Types


All exception types are subclasses of the built-in class Throwable. Immediately below
Throwable are two subclasses that partition exceptions into two distinct branches. One
branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch. There is an important subclass of Exception, called
RuntimeException. The other branch is topped by Error, which defines exceptions
that are not expected to be caught under normal circumstances by your program.

Vasavi Degree College 4


(C) www.anuupdates.org
KHK JAVA Unit-4

Checked Exception:
These exceptions are explicitly handled in the code itself with the help of try-catch
blocks. These exceptions are checked at compilation time by the java compiler. These
exceptions are extend from the ― java.lang.Exception‖ class.
Unchecked Exception:
These exceptions are not essentially handled in the program code; instead the JVM
handles such exceptions. Unchecked exceptions are extended from
―java.lang.RuntimeException‖ class.

List out some common predefined exceptions?

Sno Exception name Meaning


Caused by math errors such as division by
1 ArithmeticException
zero
Caused due to accessing the array indices
2 ArrayIndexOutOfBoundsException
which out of range
Caused due to assignment to an array
3 ArrayStoreException
element of an incompatible type.
Caused when a conversion between string
4 NumberFormatException
and fails
5 NullPointerException Caused when referring a null object

Vasavi Degree College 5


(C) www.anuupdates.org
KHK JAVA Unit-4

6 ClassCastException Caused when invalid casting of an object


Caused when trying to create an array with
7 NegetiveArraySizeException
negative size
8 NoSuchFieldException Caused when requested field does not exist
Cased when requested method does not
9 NoSuchMethodException
exist
Caused when the system runs out of stack
10 StackOverFlowException
space

Explain multiple catch Clauses with an example?


In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, you can specify two or more catch clauses, each catching
a different type of exception. When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches that of the exception is
executed. When you use multiple catch statements, it is important to remember that
exception subclasses must come before any of their superclasses. This is because a
catch statement that uses a superclass will catch exceptions of that type plus any of its
subclasses. Thus, a subclass would never be reached if it came after its superclass.
Further, in Java, unreachable code is an error.
Example:
class MultiCatch {
public static void main(String args[ ]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}

Vasavi Degree College 6


(C) www.anuupdates.org
KHK JAVA Unit-4

catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("After try/catch blocks.");
}
}

throw Statement
It is possible for your program to throw an exception explicitly, using the throw
statement. The general form of throw is

throw ThrowableInstance;

The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of the exception. If it does find a match,
control is transferred to that statement.

throws statement
If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that
exception. You do this by including a throws clause in the method’s declaration. 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. All other exceptions that a method can throw must be declared in
the throws clause. If they are not, a compile-time error will result.
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}

Vasavi Degree College 7


(C) www.anuupdates.org
KHK JAVA Unit-4

Example:
class thr{
static void demo( ) throws ArithmeticException
{
System.out.print("inside demo");
throw new ArithmeticException("division error");
}
public static void main(String args[ ]){
try{
demo();
}
catch(Exception e){
System.out.print(e.getMessage());
}
}
}

Explain finally block?


The finally block will execute whether or not an exception is thrown. If an exception
is thrown, the finally block will execute even if no catch statement matches the
exception. Any time a method is about to return to the caller from inside a try/catch
block, via an uncaught exception or an explicit return statement, the finally clause is
also executed just before the method returns. The finally clause is optional. However,
each try statement requires at least one catch or a finally clause.
Example:
class FinallyDemo {
// Through an exception out of the method.
static void procA( ) {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {

Vasavi Degree College 8


(C) www.anuupdates.org
KHK JAVA Unit-4

System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB( ) {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC( ) {
try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA( );
}
catch (Exception e) {
System.out.println("Exception caught");
}
procB( );
procC( );
}
}

Vasavi Degree College 9


(C) www.anuupdates.org
KHK JAVA Unit-4

Creating Your Own Exception Subclasses


This is quite easy to do: just define a subclass of Exception (which is, of course, a
subclass of Throwable). Your subclasses don’t need to actually implement anything—
it is their existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable. Thus, all exceptions, including those that you
create, have the methods defined by Throwable available to them.
Example:
import java.io.*;
class EvenException extends Exception{
EvenException( ) {
super("Given Number Is Even");
}
}
class OddException extends Exception{
OddException(String st) {
super(st);
}
}
class MY_Exception{
public static void main(String args[ ]) {
DataInputStream in=new DataInputStream(System.in);
int n;
try{
System.out.println("Enter Any Integer Number");
n=Integer.parseInt(in.readLine( ));
if(n%2 ==0)
throw new EvenException( );
else
throw new OddException("Given Number Is Odd Number");
}
catch(EvenException e) {
System.out.println(e.getMessage( ));

Vasavi Degree College 10


(C) www.anuupdates.org
KHK JAVA Unit-4

}
catch(OddException e) {
System.out.println(e.getMessage( ));
}
catch(IOException e) {
System.out.println(e.getMessage( ));
}
}
}

Vasavi Degree College 11


(C) www.anuupdates.org
KHK JAVA Unit-4

Multithreaded Programming
What is a multithread programming?
Multithreading is a conceptual programming model where a program (process) is
divided into two or more subprograms (processes), which can be implemented at the
same time in parallel. A thread is similar to a program that has a single flow of
control. It has beginning, a body and an end, and executes commands sequentially. A
program that contains multiple flows of control is known as multithreaded program
Advantages:
 Using multithreading you can write very efficient programs that make maximum use
of the cpu, because idle time can kept minimum.
 When a thread blocks in java program only the single thread that is blocked pauses,
all the other threads continue to run.

Differentiate between multithreading and multitasking?


Sno Multithreading Multitasking
1 It is programming concept in which It is an operating system concept in which
program or a process is divided into two multiple tasks are performed
or more subprograms or threads that are simultaneously.
executed in parallel.
2 It supports execution of multiple parts of It supports execution of multiple programs
a single program simultaneously simultaneously.
3 The processor has to switch between The processor has to switch between
different parts or threads of a program different programs or applications
4 It is highly efficient It is less efficient in comparison to
multithreading
5 It is cost –effective in case of context- It is expensive in case context-switching
switching

Vasavi Degree College 12


(C) www.anuupdates.org
KHK JAVA Unit-4

Explain Thread Life Cycle:

During the life time of a thread, there are many states it can enter. They include:
1. Newborn state.
2. Runnable state.
3. Running state.
4. Blocked state.
5. Dead state.
 A thread can be ready to run as soon as it gets the cpu time.
 A running Thread can be suspended, which temporarily suspends its activity.
 A suspended thread can then be resumed allowing it to pick up where it left off.
 At any time a thread can be terminated, which halts its execution immediately.
 Once terminated a thread can not be resumed.

New state
After the creations of Thread instance the thread is in this state but before the start( )
method invocation. At this point, the thread is considered not alive.
Runnable (Ready-to-run) state
A thread start its life from Runnable state. A thread first enters runnable state after
the invoking of start() method but a thread can return to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a thread is
waiting for a turn on the processor .

Vasavi Degree College 13


(C) www.anuupdates.org
KHK JAVA Unit-4

Running state
A thread is in running state that means the thread is currently executing. There are
several ways to enter in Runnable state but there is only one way to enter in Running
state: the scheduler select a thread from runnable pool.

Blocked
A thread can enter in this state because of waiting for the resources that are hold by
another thread. A blocked thread is considered ―not runnable‖ but not dead and
therefore fully qualified to run again.

Dead state
A thread can be considered dead when its run( ) method completes. If any thread
comes on this state that means it cannot ever run again. It is a natural death. We can
kill it by sending the stop message to it at any state thus causing a premature death to
it.

Vasavi Degree College 14


(C) www.anuupdates.org
KHK JAVA Unit-4

Explain the process of creating Threads:


Creating threads in java is simple. A new thread can created in two ways.
1. By Extending a thread class: define a class which extends Thread class and override
its run () method with the code required by the thread.
2. By implementing Runnable interface: define a class which implements Runnable
interface. The Runnable interface has only one method run( ), that is to be defined in
the method with the code to be executed by the thread.
1. By extending a thread class:
We can make our class runnable by extending the Thread class. It includes the
following steps:
 Declare the class as extending the Thread class.

Class custom_Thread extends Thread

 Implement the run( ) method that is responsible for executing the sequence of
code that the tread will execute.
Public void run( ) {
//do the work this thread was created for
}

 Create a thread object and call the start( ) method to initiate the thread
execution.

Custom_Thread th = new custom_Thread( );


th.start( );

Example:

class child extends Thread {


child( ){
super("child thread");
start( );
}
public void run( ){
try{
System.out.println("child thread started :");

Vasavi Degree College 15


(C) www.anuupdates.org
KHK JAVA Unit-4

for(int i=0;i<=5;i++)
System.out.println((Thread.currentThread()).getName() + " here..... ");
Thread.sleep(1000);
}
catch(InterruptedException e){ }
System.out.println("child thread ended :");
}
}

class custom {
public static void main ( String args[ ] ){
child c= new child( );
try{
for(int i=0;i<=5;i++)
System.out.println((Thread.currentThread()).getName() + " here..... ");
Thread.sleep(5000);
}catch( InterruptedException e ){ }
System.out.println("main thread ended :");
}
}

2. Implementing Runnable interface


Overriding the Runnable interface is one of the two way to create our own threads in
java. This interface has only one method (run( )) you place the code you want to
have the new thread execution in that method. When you create a new Runnable
object, you can pass that object to the constructor of the Thread object to create new
Thread. To do this we must perform the following steps:

 Declare the class which implements the Runnable interface.

calss custom_thread implements Runnable

Vasavi Degree College 16


(C) www.anuupdates.org
KHK JAVA Unit-4

 Implement the run ( ) method.


Public void run( ) {
// do the work this thread was created for
}

 Create a by defining an object that is instantiated from this runnable class as


the target of the thread.
custom_thread c = new custom_thread( )
Thread th= new Thread( c )

 Call the Thread’s start( ) method to run the thread.

th . start( );

Example:

class child implements Runnable{


Thread th;
child( ){
th=new Thread(this,"childthread");
System.out.println("child thread started ......");
th.start( );
}
public void run( ){
try{
for(int i=0;i<=5;i++)
System.out.println((Thread.currentThread()).getName() +" " +i);
Thread.sleep(1000);
}catch(InterruptedException e){ }
System.out.println("child thread ending ");
}}
class custom_thread {
public static void main(String args[ ]){
System.out.println("main thread started");
child c=new child( );

Vasavi Degree College 17


(C) www.anuupdates.org
KHK JAVA Unit-4

try{
for(int j=10;j>=1;j--)
System.out.println("main : "+j);
Thread.sleep(1000);
}catch(InterruptedException e){ }
System.out.println("main thread ending ");
}
}

Explain Thread Priorities?


 In the Java programming language, every thread has a priority. By default, a thread
inherits the priority of the thread that constructed it.
 You can increase or decrease the priority of any thread with the ―setPriority‖ method.

th . setPriority ( int p)

 The thread class defines three levels of Thread prioritys


MIN_PRIORITY= 1
MAX_PRIORITY=10
NORM_PRIORITY=5
 Whenever multiple threads are ready for execution , the java system choose the
highest priority thread and executes.
Example:
class counter implements Runnable {
Thread th;
int cou=0;
volatile boolean flag;
public counter(int p) {
th= new Thread(this);
th.setPriority(p);
}
public void start( ) {
flag=true;
th.start( );

Vasavi Degree College 18


(C) www.anuupdates.org
KHK JAVA Unit-4

}
public void run( ) {
while(flag)
cou++;
}
public void end( ) {
flag= false;
}
}

class th_pri {
public static void main( String args[ ] ) {
counter c1=new counter(5);
counter c2=new counter(Thread.MAX_PRIORITY );
counter c3=new counter(Thread.NORM_PRIORITY -1);
c1.start();
c2.start();
c3.start();
try {
Thread.sleep(100);
}
catch (InterruptedException e){}
c1.end( );
c2.end( );
c3.end( );
System.out.println("thread 1 counted :" +c1.cou);
System.out.println("thread 2 counted :" +c2.cou);
System.out.println("thread 3 counted :" +c3.cou);
}
}
Output
>javac th_pri.java
>java th_pri

Vasavi Degree College 19


(C) www.anuupdates.org
KHK JAVA Unit-4

thread 1 counted :29444680


thread 2 counted :2094225089
thread 3 counted :0

Write about thread synchronization:


When two or more threads access to a shared( common) 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 is achieved is called synchronization. We can synchronize our code in
two ways. Both involve the use of ―synchronized‖ keyword
1. Synchronized methods
2. Synchronized code blocks
synchronized methods:
We can serialize the access to the methods to only one thread at a time. To do this you
simply need to precede the method’s definition with the keyword synchronized.
synchronized void meth( ) {
Some thread work;
}
When we declare a method synchronized, java creates a ―monitor‖ and hands it over
the thread that calls method first time. As long as the thread holds the monitor, no
other thread can enter the synchronized section of code.
synchronized code blocks:
We use the keyword synchronized indicating the object you want to restrict access to.
The general form is
synchronized (obj)
{
//statements to be synchronized
}

Explain Inter – Thread Communication:


Inter thread communication can be defined as the exchange of messages between two
or more threads. The transfer of messages takes place before or after the change of
state of thread. Java implements inter- thread communication with help of following
methods:

Vasavi Degree College 20


(C) www.anuupdates.org
KHK JAVA Unit-4

wait( )
The method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).

final void wait( ) throws InterruptedException

notify( )
Wakes up the first thread that called wait( ) on the same object. The Object
class declaration of this method is:

final void notify( )

notifyAll( )
Wakes up all the threads that called wait( ) on the same object. the execution
of these threads happens as per priority. Highest priority thread will run first.

final void notifyAll( )

Vasavi Degree College 21


(C) www.anuupdates.org

You might also like