You are on page 1of 35

1.Define Exception.

Explain Exception Handling mechanism with an example


program.

Exception:
An exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Exception Handling:

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

• In java, exceptions are handled by using 5 keywords


1) try 2) catch 3) throw 4) throws 5) finally

1. try: It contains program statements that you want to monitor for exceptions. If an exception
occurs within the try block, it is thrown.

2. catch: Your code can catch this exception (using catch) and handle it in some rational
manner.System-generated exceptions are automatically thrown by the Java runtime system.

3. throw: To manually throw an exception, use the keyword throw.

4. thrown: Any exception that is thrown out of a method must be specified as such by a throws
clause.

5. finally: Any code that absolutely must be executed after a try block completes is put in a
finally block.

Syntax:

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
}

Here, ExceptionType is the type of exception that has occurred.

Example: demonstrate the try, catch, and finally blocks.

import java.util.*;
class Example
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Advantage of Exception Handling


The advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
that is why we use exception handling.
Difference between checked and unchecked exceptions
Checked Exception Unchecked Exception

Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.

The compiler checks a checked exception. The compiler does not check these types of

exceptions.
These types of exceptions can be handled at the These types of exceptions cannot be a catch
time of compilation.
or handle at the time of compilation, because

they get generated by the mistakes in the

program.

They are the sub-class of the exception class. They are runtime exceptions and hence are

not a part of the Exception class.

Here, the JVM needs the exception to catch and Here, the JVM does not require the exception
handle.
to catch and handle.

Examples of Checked exceptions: Examples of Unchecked Exceptions:

● File Not Found Exception ● No Such Element Exception


● No Such Field Exception ● Undeclared Throwable Exception
● Interrupted Exception ● Empty Stack Exception
● No Such Method Exception ● Arithmetic Exception
● Class Not Found Exception ● Null Pointer Exception
● Array Index Out of Bounds Exception
● Security Exception

Difference between throw and throws

Throw Throws

This keyword is used for explicitly throwing an exception. This keyword is used for declaring any

exception.

Programmers cannot disseminate checked exceptions using Programmers can disseminate checked
the throw keyword.
exceptions using throws keyword.

An instance trails the throw keyword. A class trails the throws keyword.
You have to use the throw keyword inside any method. You have to use the throws keyword with

any sign of the method.

Many exceptions cannot be thrown. Many exceptions can be declared using the

throws.

Explain exception hierarchy:


Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error.

Error: An Error is a problem that an application wll not try to catch.Error cannot be
recovered.JVM is used to indicate error created is JRE(Java Runtime
Environment).Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE).
Ex:StackOverflowError,OutOfMemoryError etc.
Exception: Exception is a condition that an application will try to catch.

Ex:IOException,ArrayIndexOutOfBoudException etc.
Based on the above hierarchy,

There are mainly two types of exceptions: checked and unchecked.

1. Checked Exception

2. Unchecked Exception

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error
are known as checked exceptions. Checked exceptions are checked at compile-time.

Ex: IOException, SQLException etc.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.

EX: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

TYPES OF ERRORS

There are 3 types of errors In java:

1.Compile-time errors

2.Run time errors

3.logical errors

COMPILE TIME ERRORS:

These errors are errors which prevents the code from compiling because of error in the syntax
such as missing a semicolon at the end of a statement or due to missing braces, class not found,
etc. These errors will be detected by java compiler and displays the error onto the screen while
compiling.

RUN TIME ERROR:

These errors are errors which occur when the program is running. Run time errors are not
detected by the java compiler. It is the JVM which detects it while the program is running.

LOGICAL ERRORS:
These errors are due to the mistakes made by the programmer. It will not be detected by a
compiler nor by the JVM. Errors may be due to wrong idea or concept used by a programmer
while coding.

What is an exception?what ca be done when it occurs?what is a cause of


excpetion?

WHAT IS AN EXCEPTION?

● An exception is a runtime error, which disrupts the normal execution flow of a


program.
● Compile time errors could not be considered as exceptions, since they are
treated as errors and not as exceptions.
● For example, Syntactical errors like missing of semicolon in the end of the
statement may result in compile time errors.
● In Java, exceptions are objects which has the information like where it occured
(class, method name,line number), type of the error, state of the program when
the error occurred

WHAT COULD BE DONE WHEN AN EXCEPTION OCCURS?

One of the following could be done when an exception occurs.

● Report it to the user by printing a message.


● Handle the error, if something could be done to rectify.

CAUSE OF AN EXCEPTION:

● Due to environmental conditions (uncertain):


● Due to bad programming logic.
● Due to a wrong input (unsupported by the program) provided by the user / client.

What is the use of java try and catch?Explain.


The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.

The try and catch keywords come in pairs:

Syntax

try
{

// Block of code to try

catch(Exception e)

// Block of code to handle errors

Example:

This will generate an error, because myNumbers[10] does not exist.

class Main
{
public static void main(String[ ] args)
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

The output generates an error.

If an error occurs, we can use try...catch to catch the error and execute some code to
handle it:

Example:

class Main
{
public static void main(String[ ] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
}
}
}

The output will be:

Something went wrong.

Explain nested try-catch block with an example program.

Java Nested try block


The try block within a try block is known as nested try block in java.

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.

Syntax:
....

try

statement 1;

statement 2;

try

statement 1;

statement 2;
}

catch(Exception e)

catch(Exception e)

....

Java nested try example

class Excep6

public static void main(String args[])

try

try

System.out.println("going to divide");

int b =39/0;

}
catch(ArithmeticException e){System.out.println(e);

try

int a[]=new int[5];

a[5]=4;

catch(ArrayIndexOutOfBoundsException e)

System.out.println(e);

System.out.println("other statement);

catch(Exception e)

System.out.println("handeled");

System.out.println("normal flow..");

}
Explain finally block with an example.
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Why use java finally

● Finally block in java can be used to put "cleanup" code such as closing a file,

closing connection etc.

Syntax
Try
{
//Statements that may cause an exception
}
Catch
{
//Handling exception
}
finally
{
//Statements to be executed
}

Example of finally block

Here the exception as occurred in try block which has been handled in catch

block, after that finally block got executed.

class Example
{
public static void main(String args[])
{
try
{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e)
{
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
Finally
{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}

Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Explain Multi-catch block with an example.
A try block can be followed by one or more catch blocks. Each catch block must contain

a different exception handler. So, if you have to perform different tasks at the

occurrence of different exceptions, use java multi-catch block.

● At a time only one exception occurs and at a time only one catch block is

executed.

● All catch blocks must be ordered from most specific to most general, i.e. catch

for ArithmeticException must come before catch for Exception.

Example
public class MultipleCatchBlock1
{

public static void main(String[] args)


{

try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

Difference between final, finally and finalize

N final finally finalize

1) Final is used to apply restrictions Finally is used to place Finalize is used to

on class, method and variable. important code, it will perform clean up

Final class can't be inherited, final be executed whether processing just

method can't be overridden and exception is handled or before object is

final variable value can't be not. garbage collected.

changed.

2) Final is a keyword. Finally is a block. Finalize is a

method.

Java final example

class FinalExample{

public static void main(String[] args){

final int x=100;

x=200;//Compile Time Error

}}

Java finally example


class FinallyExample{

public static void main(String[] args){

try{

int x=300;

}catch(Exception e){System.out.println(e);}

finally{System.out.println("finally block is executed");}

}}

Java finalize example

class FinalizeExample{

public void finalize(){System.out.println("finalize called");}

public static void main(String[] args){

FinalizeExample f1=new FinalizeExample();

FinalizeExample f2=new FinalizeExample();

f1=null;

f2=null;

System.gc();

}}

What is User Defined Exception in Java?

or
write the purpose of extending “exception” class with example program.
We can create our own exception class and throw that exception using throw

keyword. These exceptions are known as user-defined or custom exceptions.

This can be done by extending the class Exception.

Example: To created a User-Defined Exception Class

class JavaException{

public static void main(String args[]){

try{

throw new MyException(2);

// throw is used to create a new exception and throw

it.

catch(MyException e){

System.out.println(e) ;

class MyException extends Exception{

int a;

MyException(int b) {
a=b;

public String toString()

return ("Exception Number = "+a) ;

output -

● User-defined exception must extend Exception class.

● The keyword “throw” is used to create a new Exception and throw it to the

catch block

Explain the concept of synchronization in Java with an example

program.

• Synchronization in java is the capability to control the access of multiple threads to

any shared resource.

• Java Synchronization is better option where we want to allow only one thread to

access the shared resource.


• The synchronization is mainly used to to prevent thread interference and to prevent

consistency problem.

Example:

// This program uses a synchronized block.


class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run()
{
synchronized(target)
{
// synchronized block
target.call(msg);
}
}
}
class Synch1
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}

Define deadlock? Write a java program to create deadlock situation java.

Deadlock is a situation where a set of processes are blocked because each process

is holding a resource and waiting for another resource acquired by some other

process.

Example:

class Shared
{
synchronized void Resource1(Shared s2)
{
System.out.println("Resource1 is used");
try { Thread.sleep(1000); }
catch (InterruptedException e)
{
System.out.println(e);
}
s2.Resource2(this);
System.out.println("Resource1 is end");
}
synchronized void Resource2(Shared s1)
{
System.out.println("Resource2 is used");
try { Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
s1.Resource1(this);
System.out.println("Resource2 is end");
}
}
class Thread1 extends Thread
{
private Shared s1, s2;
public Thread1(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}
public void run() {
s1.Resource1(s2);
}
}
class Thread2 extends Thread
{
private Shared s1, s2;
public Thread2(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}
public void run()
{
s2.Resource2(s1);
}
}
public class DeadlockDemo3
{
public static void main(String[] args)
{
Shared s1 = new Shared();
Shared s2 = new Shared();
Thread1 t1 = new Thread1(s1, s2);
t1.start();
Thread2 t2 = new Thread2(s1, s2);
t2.start();
}
}

Why use Synchronization


The synchronization is mainly used to

1. To prevent thread interference.

2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization

2. Thread Synchronization

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread

communication.

1. Mutual Exclusive

1. Synchronized method.

2. Synchronized block.
3. static synchronization.

2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing

data. This can be done by three ways in java:

1. by synchronized method

2. by synchronized block

3. by static synchronization

Inter-thread communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized

threads to communicate with each other.

Cooperation (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.It is implemented by following methods of Object

class:

● wait()

● notify()

● notifyAll()

Difference between wait and sleep?


wait() sleep()

wait() method releases the lock sleep() method doesn't release the

lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or after the specified amount of time,

notifyAll() methods sleep is completed.

Example of inter thread communication in java

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...");

try{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 Test{

public static void main(String args[]){

final Customer c=new Customer();

new Thread(){

public void run(){c.withdraw(15000);}


}.start();

new Thread(){

public void run(){c.deposit(10000);}

}.start();

}}

Output:

going to withdraw...

Less balance; waiting for deposit...

going to deposit...

deposit completed...

withdraw completed
Draw and explain different states in thread life cycle
with neat sketch

Life cycle of a thread

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

A thread can be in one of the five states. According to sun, there is only 4 states in

thread life cycle in java new, runnable, non-runnable and terminated. There is no

running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as

follows:

1. New

2. Runnable

3. Running

4. Non-Runnable (Blocked)

5. Terminated
1) New

The thread is in new state if you create an instance of Thread class but before the

invocation of start() method.


2) Runnable

The thread is in runnable state after invocation of start() method, but the thread

scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

Explain the two ways to create a thread.Explain with


programs.

There are two ways to create a thread in Java:


1) By extending Thread class.
2) By implementing Runnable interface.

Method 1: Thread creation by extending Thread class


Example 1:

class MultithreadingDemo extends Thread


{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:

My thread is in running state.

Method 2: Thread creation by implementing Runnable Interface

A Simple Example

class MultithreadingDemo implements Runnable{

public void run(){

System.out.println("My thread is in running state.");

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

Thread tobj =new Thread(obj);

tobj.start();

}
Output:

My thread is in running state.

Write a java program to copy the content from one file to another file

using Byte stream classes.


import java.io.*;

class FileDemo

public static void main(String args[]) throws IOException

int ch;

FileInputStream fin=null;

FileOutputStream fout=null;

try

fin=new FileInputStream("D:/java/alphabets.txt");

fout=new FileOutputStream("D:/java/newalphabets.txt");

ch = fin.read();

while(ch !=-1)

fout.write((char)ch);

ch = fin.read();

System.out.println("Copy completed");

catch(Exception e)

System.out.println("File is not found");

finally
{

fin.close();

fout.close();

Output:

Copy completed

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:

• A new thread starts(with new callstack).

• The thread moves from New state to the Runnable state.

• When the thread gets a chance to execute, its target run() method will run.

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10.

In most cases, thread schedular schedules the threads according to their priority

(known as preemptive scheduling). But it is not guaranteed because it depends on JVM

specification that which scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY


3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1

and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread

public void run()

System.out.println("running thread name is:"+Thread.currentThread().getName());

System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

public static void main(String args[])

TestMultiPriority1 m1=new TestMultiPriority1();

TestMultiPriority1 m2=new TestMultiPriority1();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

Output:
running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1

You might also like