0% found this document useful (0 votes)
12 views23 pages

JAVA Unit-V (3)

The document discusses exception handling and types of errors in Java, categorizing them into syntax errors, runtime errors, and logic errors. It explains the difference between checked and unchecked exceptions, along with the keywords used in Java for exception handling: try, catch, throw, throws, and finally. Additionally, it provides examples of built-in exceptions and user-defined exceptions, illustrating how to manage and handle exceptions in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

JAVA Unit-V (3)

The document discusses exception handling and types of errors in Java, categorizing them into syntax errors, runtime errors, and logic errors. It explains the difference between checked and unchecked exceptions, along with the keywords used in Java for exception handling: try, catch, throw, throws, and finally. Additionally, it provides examples of built-in exceptions and user-defined exceptions, illustrating how to manage and handle exceptions in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT-V

Exception Handling & MultiThreaded

Types of Errors

Que:
1. List and explain different types of errors.
2. Explain types of errors with example.
3. List types of Errors in exceptional handling and explain any one of them.
4. List types of error in Java.
Ans:

 There are basically three types of errors that may arise during computer programs
execution:

1. Syntax errors
2. Runtime errors
3. Logic errors

1. Syntax errors
 Syntax Errors, also known as Compilation errors are the most common type of errors.
 Most Syntax errors are caused by mistakes that you make when writing code.
 Common examples are:
 Misspelled variable and function names
 Missing semicolons
 Improperly matches parentheses, square brackets, and curly braces
 Incorrect format in selection and loop statements

2. Runtime errors
 Run-time errors are those that appear only after you compile and run your code. It will
occur when your program attempts an operation that is impossible to carry out.
 You can fix most run-time errors by rewriting the faulty code, and then recompiling and
running it.
 Common examples are:
 Trying to divide by a variable that contains a value of zero
 Trying to open a file that doesn't exist
 There is no way for the compiler to know about these kinds of errors when the program is
compiled.

3. Logic errors
 Your code may compile and run without any Syntax Errors or Run-time Errors, but the
output of an operation may produce unwanted or unexpected results in response to user
actions. These types of errors are called Logic Errors.
 Common examples are:
 Multiplying when you should be dividing
 Adding when you should be subtracting
 Opening and using data from the wrong file
 Displaying the wrong message

Page 1 of 23
Exception
Que:
1. Compare checked and Unchecked Exception.
Ans:
 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
terminates abnormally. Therefore, these exceptions are to be handled.
 Following are some scenarios where an exception occurs.
 A user has entered an invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications or the JVM has run
out of memory.

 Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.

 Based on these, we have 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.

 For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.

2. Unchecked exceptions

 An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions.

 These include programming bugs, such as logic errors or improper use of


an API.

 For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.

Page 2 of 23
3. Errors

 Error is a problem that arises, which is not under the control of the user or
the programmer.

 For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.

 These are not exceptions at all.

Differentiate between Exception and Error


Sr.
Error Exception
No.
1 Error is a problem that arises, which is not Exception is a problem that arises during
under the control of the user or the the execution of a program.
programmer.
Error is which nobody can control or guess. Exception can be guessed and so it can be
2
when it occurs, so error cannot be handled. handled.
3 Error can Terminates the program Exception do not terminate the program.
An Exception can be caught and recovered:
An Error is unrecoverable:
ArrayIndexOutOfBoundsException means
4 OutOfMemoryError means that the JVM has
you tried to access a position of an Array
no more memory to contain
that does not exist - no big deal.
Error message is standard given by JVM. Exception will give user friendly message
5
which is defined in exception handling.
For example: For Example:
6
thread dead,out of memory, overflow. Divided by Zero, File doesn’t Exist

Page 3 of 23
Exception Handling in Java

Que:
1. Explain Exception Handling.
2. Explain basic concept of Exception Handling.
Ans:
 Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
 Program statements that you want to monitor for exceptions are contained within a try
block.
 If an exception occurs within the try block, it is thrown. Your code can catch this
exception (using catch) and handle it.
 System-generated exceptions are automatically thrown by the Java run-time system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws
clause.
 Any code that absolutely must be executed after a try block completes is put in a finally
block.
 This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed after try block ends
}

Try…Catch
Que:
1. Explain Try and Catch with suitable example.
2. Explain ‘try’ and ‘catch’ statements in exceptional handling of Java language.
3. Write a program and explain try…catch block.
4. Explain ArrayIndexOutOfBound Exception in Java with example.
Ans:

Page 4 of 23
 Code that you want to monitor, put inside in Try block.
 Immediately following the try block, include a catch block that specifies the exception
type that we wish to catch.
 Following program includes try block and catch block which processes the
ArithmeticException generated by the division-by-zero.
 Example,
class AE
{
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.");
}
}
 Once an exception is thrown,program control transfers out of the try block into catch
block.

Multiple Catch Blocks


Que:
1. Explain Multiple Catch block with program example.
2. Explain multiple catch blocks with example.
Ans:

 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 block.
 When an exception is thrown, each catch statement is inspected in order, and whose type
is matches that of the exception is executed.
 After one catch statement executed, the other are bypassed and execution continues after
the try/catch block.
 Syntax
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
Page 5 of 23
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
 Example,
class ME
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
int c[]={1};
c[42]=99;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero." + e );
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bound" +e );
}

System.out.println("After catch statement.");


}
}

Throw, Throws and Finally


Que:
1. Explain throw & throws with example.
2. Explain throw and finally in Exception Handling of java language.
3. Compare following:
(ii) throwVs throws
4. Explain following
(i) throws (ii) checked exception
5. Explain following
(i) throw (ii) finally
Page 6 of 23
Ans:

Throw
 System-generated exceptions are automatically thrown by the Java run-time system.
 To manually throw an exception, the throw keyword is used.
 it is used to explicitly throw exception in java.
 The general form of throw is shown here:

throw ThrowableInstance;

 Here, ThrowableInstance must be an object of type Throwable or a subclass of


Throwable.
 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 exception.
 If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on.
 Example,

class throwDemo
{
static void validate(int age)
{
try
{
if(age<16)
{
throw new ArithmeticException("Invalid Age");

}
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}

public static void main(String args[])


{
int age=10;

validate(age);
}
}

Page 7 of 23
Throws

 The throws keyword is used to declare that a method may throw one or some
exceptions.
 It can propagate exception to the calling method.
 Calling method must have to catch the exception which is thrown by the throws
keyword.
 Programmer has to handle the thrown exception.
 It can throws checked exception.
 All other exceptions that a method can throw must be declared in the throws clause.
 The throws keyword must be followed by Throwable class or one of its subclasses.
 This is the general form of a method declaration that includes a throws clause:

type method-name (parameter-list) throws Exception1, Exception2


{
// body of method
}

 Exception1, Exception2, …are the exception class, must be subclass


of Throwable class.
 For Example:
class testThrow
{
static void divide() throws ArithmeticException
{
int a=8,d=0;
a=42/d;
}

public static void main(String args[])


{
try
{
divide();
}

catch(ArithmeticException e)
{
System.out.println("Please Enter Valid Data");
}

}
}

Finally
Page 8 of 23
 Finally creates a block of code that will be executed after a try/catch block has completed.
 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.
 The finally clause is optional. The finally block follows a try block or a catch block.
 Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
finally
{
// The finally block always executes.
}

 Example:
class AE
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("The finally statement is executed");

}
System.out.println("After catch statement.");

}
}

Page 9 of 23
Difference between throw and throws
Sr. throw throws
no.
1) throw keyword is used to explicitly throws keyword is used to declare an exception.
throw an exception.
3) Throw is used within the method. Throws is used with the method signature.
4) You cannot throw multiple exceptions. You can declare multiple exceptions.
5) Used only to throw but can not Throws is used to propagate exception to the
propagate exception to the calling calling method.
method.
6) Throw is followed by an instance. Throws is followed by class.
7) Public void m1() Public void m1() throws ArithmeticException
{ {
Throw new ArithmeticException();
} }

Built-in Exceptions
Que:
1. List any four inbuilt exceptions.
2. List four different inbuilt exceptions of Java.
Ans:
 Built-in exceptions are the exceptions which are available in Java libraries.
 Following is the list of Java Checked Exceptions:

Sr. Exception & Description


No.

1
ArithmeticException
Arithmetic error, such as divide-by-zero.

2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3
ArrayStoreException
Assignment to an array element of an incompatible type.

4
ClassCastException

Page 10 of 23
Invalid cast.

5
IllegalArgumentException
Illegal argument used to invoke a method.

6
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.

7
IllegalStateException
Environment or application is in incorrect state.

8
IllegalThreadStateException
Requested operation not compatible with the current thread state.

9
IndexOutOfBoundsException
Some type of index is out-of-bounds.

10
NegativeArraySizeException
Array created with a negative size.

11
NullPointerException
Invalid use of a null reference.

12
NumberFormatException
Invalid conversion of a string to a numeric format.

13
SecurityException
Attempt to violate security.

14
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.

15
UnsupportedOperationException
An unsupported operation was encountered.

Following is the list of Java UnChecked Exceptions Defined in java.lang.


Sr.No. Exception & Description
Page 11 of 23
1
ClassNotFoundException
Class not found.

2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.

3
IllegalAccessException
Access to a class is denied.

4
InstantiationException
Attempt to create an object of an abstract class or interface.

5
InterruptedException
One thread has been interrupted by another thread.

6
NoSuchFieldException
A requested field does not exist.

7
NoSuchMethodException
A requested method does not exist.

User-Defined Exception
 Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
 For example:

class MyException extends Exception


{
public MyException(String msg)
{
super(msg);
}
}

class ThrowExcep
{
static void div() throws MyException
{
int a=2,b=0;
if(b==0)

Page 12 of 23
throw new MyException("demo");
else
{
int ar=a/b;
}
}
public static void main(String args[])
{
try
{
div();
}
catch(MyException e)
{
System.out.println("Divide");
}
}
}
Main thread in Java
Que:
1. Define Thread in Java.
2. Define thread. State two ways to create a thread.
3. Explain ‘Extending Thread class’ in Java.
4. What is Thread? List different methods used to create Thread. Explain Thread life cycle.
Ans:
 Java provides built-in support for multithreaded programming. A multi-threaded program
contains two or more thread that can run concurrently.
Definition:
 Thread can be called lightweight process. Thread requires less resources to create and
exists in the process, thread shares the process resources.
 When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of our program, because it is the one that is executed when our
program begins.
Properties :
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it performs various shutdown
actions.

Creating Thread

 We can create thread by creating object of type thread.


 Java defines two ways to create thread.

1.Implementing Runnable Interface

2.Extending Thread Class

Page 13 of 23
1) Implementing Runnable Interface

 The easiest way to create a thread is to create a class that implements


the Runnable interface.

 To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
public void run( );

 Inside run( ), we will define the code that constitutes the new thread.
 To execute the run() method by a thread, pass an instance of ABC to a Thread in its
constructor.

 Example:
class ABC implements Runnable
{
public void run()
{
System.out.println("ABC running");
}
}
class ThreadRunnable
{
Public static void main(String args[])
{
ABC ob1=new ABC();
Thread t1 = new Thread(ob1);
t1.start();
}
}

 When the thread is started it will call the run() method of the MyClass instance instead of
executing its own run() method.
 The above example would print out the text “ABC running“.

2.Extending Thread Class

 In this method, create a new class that extends Thread.


 Then override the run() method and create an instance of that class.
Page 14 of 23
 After that, call start() method to execute run() method.
 Example:

class ABC extends Thread


{
public void run()
{
System.out.println("ABC running");
}
}

class ThreadExtend
{
public static void main(String args[])
{
ABC t1 = new ABC();
t1.start();
}
}
 When the run() method executes it will print out the text “ABC running“.

Multiple Threads

 Our program can affect as many threads as it needs. Let’s see how we can create multiple
threads.

1. Multiple thread by Runnable Interface


class ABC implements Runnable
{
String name;

ABC(String str)
{
name=str;
Thread t1=new Thread(this);
t1.start();

}
public void run()
{
try
Page 15 of 23
{
for(int i=0;i<5;i++)
{
System.out.println(name + " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}

class multiThread
{
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
ABC ob2=new ABC("Thread2");

2) Multiple Thread By extending Thread class

class ABC extends Thread


{

String name;

ABC(String str)
{
name=str;
start();

public void run()


{

try
{
for(int i=0;i<5;i++)
{

System.out.println(name + " is Running: "+i);

Page 16 of 23
Thread.sleep(1000);

}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}

class multiThread
{
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
ABC ob2=new ABC("Thread2");

}
}

Life Cycle of Thread

Que:
1. Explain life cycle of a thread.
2. Explain life cycle of thread in Java.
3. Describe the complete life cycle of a thread.
Ans:
 Following diagram shows Life Cycle of Thread.

New:
o The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
Page 17 of 23
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.
Running:
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.
Terminated:
o A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

Thread Priority
Que:
1. Explain thread priorities with suitable example.
2. List different thread priorities.
3. How do we set priorities for thread?
Ans:

 In a Multi threading environment, thread scheduler assigns processor to a thread based on


priority of thread.
 Whenever we create a thread in Java, it always has some priority assigned to it.
 Priority can either be given by JVM while creating the thread or it can be given by programmer
explicitly.
 Accepted value of priority for a thread is in range of 1 to 10.
 There are 3 static variables defined in Thread class for priority.

1. public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
2. public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.

 Get and Set Thread Priority:

1. public final int getPriority():


o java.lang.Thread.getPriority() method returns priority of given thread.

2. public final void setPriority(int newPriority):


o java.lang.Thread.setPriority() method changes the priority of thread to the value
newPriority.
o This method throws IllegalArgumentException if value of parameter newPriority
goes beyond minimum(1) and maximum(10) limit.

 Examples of getPriority() and setPriority

class ABC extends Thread


{
Page 18 of 23
public void run()
{
System.out.println("ABC running");
}
}

class ThreadExtend
{
public static void main(String args[])
{
ABC t1 = new ABC();
t1.start();

System.out.println(t1.getPriority());

t1.setPriority(2);

System.out.println(t1.getPriority());

System.out.println(Thread.currentThread().getName());
}

Synchronization
Que:
1. Explain Synchronization in Thread.
2. What is Synchronization? When do we use it?
3. Explain thread synchronization.
Ans:
 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 by which this is
achieved is called Synchronization.
 There are two way to achieve synchronizarion

1) Using Synchronized Methods


2) Using Synchronized block
1.Using Synchronized Methods
To restrict to access of same method to only one thread at a time,we simply need to precede
method definition with the keyword synchronized.

Example:

class XYZ
{
Page 19 of 23
synchronized public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{

System.out.println(name+ " is Running: "+i);

Thread.sleep(1000);

}
}

catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}

class ABC extends Thread


{

String name;
XYZ syob1;

ABC(XYZ ob1,String str)


{
syob1=ob1;
name=str;
start();

public void run()


{

syob1.display(name);

}
}

class SyncMethodThread
{
public static void main(String args[])

Page 20 of 23
{
XYZ syob1=new XYZ();

ABC ob1=new ABC(syob1,"Thread1");


ABC ob2=new ABC(syob1,"Thread2");
}
}

2) Using synchronized block


 General form of synchronized statement
Synchronized(object)
{
//statements to be Synchronized
}
 Object is a reference to the object being synchronized.
 Example:

class XYZ
{
public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{

System.out.println(name+ " is Running: "+i);

Thread.sleep(1000);

}
}

catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}

class ABC extends Thread


{

String name;
XYZ syob1;

Page 21 of 23
ABC(XYZ ob1,String str)
{
syob1=ob1;
name=str;
start();

public void run()


{

synchronized(syob1)
{

syob1.display(name);
}
}
}

class SyncThread
{
public static void main(String args[])
{
XYZ syob1=new XYZ();

ABC ob1=new ABC(syob1,"Thread1");


ABC ob2=new ABC(syob1,"Thread2");

}
}

Methods of thread class

Method Description

setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority

isAlive() checks if thread is still running or not

join() Wait for a thread to end

Page 22 of 23
Method Description

run() Entry point for a thread

sleep() suspend thread for a specified time

start() start a thread by calling run() method

Page 23 of 23

You might also like