Exception Handling (4) (3436)
Exception Handling (4) (3436)
Exception Handling (4) (3436)
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:
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.
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
}
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...");
}
}
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
program.
They are the sub-class of the exception class. They are runtime exceptions and hence are
Here, the JVM needs the exception to catch and Here, the JVM does not require the exception
handle.
to catch and handle.
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
Many exceptions cannot be thrown. Many exceptions can be declared using the
throws.
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,
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.
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.
TYPES OF ERRORS
1.Compile-time errors
3.logical 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.
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?
CAUSE OF AN EXCEPTION:
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Syntax
try
{
catch(Exception e)
Example:
class Main
{
public static void main(String[ ] args)
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // 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.");
}
}
}
Syntax:
....
try
statement 1;
statement 2;
try
statement 1;
statement 2;
}
catch(Exception e)
catch(Exception e)
....
class Excep6
try
try
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e){System.out.println(e);
try
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.
● Finally block in java can be used to put "cleanup" code such as closing a file,
Syntax
Try
{
//Statements that may cause an exception
}
Catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
Here the exception as occurred in try block which has been handled in catch
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
● 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
Example
public class MultipleCatchBlock1
{
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
changed.
method.
class FinalExample{
}}
try{
int x=300;
}catch(Exception e){System.out.println(e);}
}}
class FinalizeExample{
f1=null;
f2=null;
System.gc();
}}
or
write the purpose of extending “exception” class with example program.
We can create our own exception class and throw that exception using throw
class JavaException{
try{
it.
catch(MyException e){
System.out.println(e) ;
int a;
MyException(int b) {
a=b;
output -
● The keyword “throw” is used to create a new Exception and throw it to the
catch block
program.
• Java Synchronization is better option where we want to allow only one thread to
consistency problem.
Example:
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();
}
}
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.
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
1. by synchronized method
2. by synchronized block
3. by static synchronization
running in its critical section and another thread is allowed to enter (or lock) in the
class:
● wait()
● notify()
● notifyAll()
wait() method releases the lock sleep() method doesn't release the
lock.
class Customer{
int amount=10000;
System.out.println("going to withdraw...");
if(this.amount<amount){
try{wait();}catch(Exception e){}
this.amount-=amount;
System.out.println("withdraw completed...");
System.out.println("going to deposit...");
this.amount+=amount;
notify();
class Test{
new Thread(){
new Thread(){
}.start();
}}
Output:
going to withdraw...
going to deposit...
deposit completed...
withdraw completed
Draw and explain different states in thread life cycle
with neat sketch
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
The thread is in runnable state after invocation of start() method, but the 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 Simple Example
tobj.start();
}
Output:
Write a java program to copy the content from one file to another file
class FileDemo
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)
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:
• When the thread gets a chance to execute, its target run() method will run.
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
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:
running thread name is:Thread-0