Exception Handling in Java

Exception Handling

 The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be
maintained.



Fundamentals exception types-

we have three categories of Exceptions. You need to understand them to know how exception handling works in Java.
  •  Checked exceptions − A checked excepÆŸon is an excepÆŸon that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these 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.
Example

import java.io.File;

import java.io.FileReader;

public class FilenotFound_Demo {

 public static void main(String args[]) { 
 File file = new File("E://file.txt");
 FileReader fr = new FileReader(file);
}
}

  •  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. Runtime exceptions are ignored at the time of
    compilation.
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.

Example
public class Unchecked_Demo {

 public static void main(String args[]) {
 int num[] = {1, 2, 3, 4};

 System.out.println(num[5]);
 }
}

Errors − These are not excepÆŸons at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Uncaught exceptions-

If you do not handle a runtime exception in your program, the default behavior  will be to terminate the program and dump the call stack trace on the console.  Java provides an elegant mechanism of handling Runtime Exceptions that you  might have not handled in your program. UncaughtExceptionHandler can be  defined at three levels. From highest to lowest they are: 
1. Thread.setDefaultUncaughtExceptionHandler 
2. ThreadGroup.uncaughtException 
3. Thread.setUncaughtExceptionHandler 
Uncaught exception handling is controlled first by the thread, then by the  thread’s Thread Group object and finally by the default uncaught exception  handler.

Throw-

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

Example

import java.io.*;
public class className {

 public void deposit(double amount) throws RemoteException {
 // Method implementation
 throw new RemoteException();
 }
 // Remainder of class definition
}

Final-

The finally block follows a try block or a catch block. A finally block of code  always executes, irrespective of occurrence of an Exception. 
Using a finally block allows you to run any cleanup-type statements that you  want to execute, no matter what happens in the protected code. 
A finally block appears at the end of the catch blocks and has the following 
syntax −
syntax

try {
 // Protected code
} catch (ExceptionType1 e1) {
 // Catch block
} catch (ExceptionType2 e2) {
 // Catch block
} catch (ExceptionType3 e3) {
 // Catch block
}finally {
 // The finally block always executes.
}

Built in exception-

Java defines several exception classes inside the standard package java.lang.

Java defines several other types of exceptions that relate to its various class libraries. Following is the list of Java Unchecked RuntimeException.

Creating your own exceptions-

You can create your own exceptions in Java. Keep the following points in mind  when writing your own exception classes −
  •  All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the
  • RuntimeException class.
We can define our own Exception class as below −
class MyException extends Exception {
}

You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. The
following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example


Multithreaded programming-

Fundamental-

  •  Java is a multi-threaded programming language which means we can
    develop multi-threaded program using Java. A multi-threaded program
    contains two or more parts that can run concurrently and each part can
    handle a different task at the same time making optimal use of the
    available resources specially when your computer has multiple CPUs.

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life  cycle of a thread
Following are the stages of the life cycle −
  •  New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. 
  •  Runnable − AÅŒer a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. 
  •  Waiting − SomeÆŸmes, a thread transiÆŸons to the waiÆŸng 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.
  • Timed Waiting − A runnable thread can enter the ÆŸmed waiÆŸng state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  •  Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Java thread model:

Java thread model can be defined in the following three sections:

Thread Priorities

Each thread has its own priority in Java. Thread priority is an absolute integer value. Thread priority decides only when a thread switches from one running thread to next, called context switching. Priority does increase the running time of the thread or gives faster execution.

Synchronization

Java supports an asynchronous multithreading, any number of thread can run simultaneously without disturbing other to access individual resources at different instant of time or shareable resources. But some time it may be possible that shareable resources are used by at least two threads or more than two threads, one has to write at the same time, or one has to write and other thread is in the middle of reading it. For such type of situations and circumstances Java implements synchronization model called monitor. The monitor was first defined by C.A.R. Hoare. You can consider the monitor as a box, in which only one threadcan reside. As a thread enter in monitor, all other threads have to wait until that
thread exits from the monitor. In such a way, a monitor protects the shareable resources used by it being manipulated by other waiting threads at the same instant of time. Java provides a simple methodology to implement synchronization.

Messaging

A program is a collection of more than one thread. Threads can communicate with each other. Java supports messaging between the threads with lost-cost. It provides methods to all objects for inter-thread communication. As a thread exits from synchronization state, it notifies all the waiting threads.

Thread class-

Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of Java.

Runnable interface-

If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −

Step 1
As a first step, you need to implement a run() method provided by
a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −
public void run( )

Step 2
As a second step, you will instantiate a Thread object using the following
constructor −

Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnableinterface and threadName is the name given to the new thread


Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −
void start();
Example
Here is an example that creates a new thread and starts running it −

Interthread communication-

Interthread communication is important when you develop an application wheretwo or more threads exchange some information.
There are three simple methods and a little trick which makes thread
communication possible. All the three methods are listed below −

These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.

Suspended Resuming and stopping thread-

Core Java provides complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed, or stopped completely based on your requirements. There are various static methods which you can use on thread objects to control their behavior. Following table lists down those methods – 


Be aware that the latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives.

Next Unit- Input/output



Post a Comment

Previous Post Next Post