Managing Errors and Exceptions: What Is An Error? Explain Types of Errors?
Managing Errors and Exceptions: What Is An Error? Explain Types of Errors?
Managing Errors and Exceptions: What Is An Error? Explain Types of Errors?
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.
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:
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);
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
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.
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
}
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());
}
}
}
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( );
}
}
}
catch(OddException e) {
System.out.println(e.getMessage( ));
}
catch(IOException e) {
System.out.println(e.getMessage( ));
}
}
}
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.
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 .
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.
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.
Example:
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 :");
}
}
th . start( );
Example:
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 ");
}
}
th . setPriority ( int p)
}
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
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( ).
notify( )
Wakes up the first thread that called wait( ) on the same object. The Object
class declaration of this method is:
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.