Thursday, August 29, 2013

Exception Handling - Examples.


/* Unchecked java.lang.ArithmeticException: / by zero will terminates the program*/

public class Exception_1
    {
        public static void main(String args[])
            {
                int a=5,b=0;
                System.out.println(a/b);
                System.out.println("\nThe - ArithmeticException() / divide by 0 will ");
            }
   }

Output : Following exception will be thrown at the line “System.out.println(a/b);”

java.lang.ArithmeticException: / by zero
          at Exception_1.main(Exception_1.java:8)

Users Defined Exception :

/*Userdefined Exception */
    public class Exception_2
        {
                public static void main(String args[])
                    {
                        int stock_qty = 500,Sold = 400;
                        System.out.println("\nCurrent Stock : "+stock_qty);
                        if (stock_qty < Sold)
                            {
                                ArithmeticException AE = new ArithmeticException("Stock is not Available");
                                throw AE;
                            }
                        else
                            {
                                stock_qty=stock_qty-Sold;
                                System.out.println("Product Sold and new Stock is "+stock_qty);
                            }
                   }
         }
Output: When,   Sold =400 :

Current Stock : 500
Product Sold and new Stock is 100

Output : Whem, Sold = 600 :

java.lang.ArithmeticException: Stock is not Available
          at Exception_2.main(Exception_2.java:10)

/* Input/Output Exception without try/catch Block */

import java.io.*;
    class Exception_3
        {
            public static void main(String args[])throws IOException
                {
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    int Num;
                    System.out.print("Enter a Number : ");
                    Num=Integer.parseInt(br.readLine());
                    System.out.println("\nNumber Inputted : "+Num);
                }
        }        

Output:  If anything else than an integer value given as input –

Enter a Number : e

java.lang.NumberFormatException: For input string: "e"
          at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
          at java.lang.Integer.parseInt(Integer.java:447)
          at java.lang.Integer.parseInt(Integer.java:497)
          at Exception_3.main(Exception_3.java:10)
Output : When integer value given as input –

Enter a Number : 12

Number Inputted : 12


/* Input/Output Exception and FileNotFound Exception */

import java.io.*;
    public class Exception_4
        {
            public static void main(String args[])
                {
                    try {
                            File Fil = new File("Data.dat");
                            FileInputStream fis = new FileInputStream(Fil);
                            BufferedReader BR = new BufferedReader(new InputStreamReader(fis));
                            System.out.print("Enter a No. ");
                            int Num = Integer.parseInt(BR.readLine());
        
                        }
                   catch (FileNotFoundException FE)
                        {
                            System.out.println(FE);
                        }                         
                   catch (IOException IE)
                        {
                            System.out.println(IE);
                        }
                      
               }
      }

Output :

java.io.FileNotFoundException: Data.dat (The system cannot find the file specified)

/*Multiple Catch Block with Finally Block*/

public class Exception_5
        {
            public static void main(String args[])
                {
                    int Num=5;
                    try
                        {
                            Num= Num/0;
                        }
                    catch(Exception Exp)
                        {
                            System.out.println("Catch Block [cause : division by zero ]");
                        }
                    finally
                        {
                            System.out.println("Finally Block, Value of Num "+Num);
                        }
                    try
                        {
                            Num =6;
                            Num = Num/2;
                        }
                    catch(Exception Exp)
                        {
                            System.out.println("Catch Block [This one will not execute]");
                        }
                    finally
                        {
                            System.out.println("Finally Block, Value of Num "+Num);
        }
    }
}


Output :

Catch Block [cause : division by zero ]
Finally Block, Value of Num 5
Finally Block, Value of Num 3




Thursday, August 22, 2013

Java Exceptions & Exception Handling



Java exception handling is a Java application that helps to handle the error occurred in different phases. Whenever any error occurs an exception is thrown. Java exceptions are the errors that occur while executing a program and these occurs for different reason like when any invalid data entered as input, for a non-existing file is asked to access etc. Java exception is either generated by the JVM (Java Virtual Machine) or it is generated by the code resultant from a throw statement. Exception is an inbuilt class in the default package known as java.lang. The exception handling is a significant part of Java programming.

Types of Exception

There are two types of exception
1.       Checked Exception
2.       Unchecked Exception.

Checked exception
 
A checked exception is any subclass of Exception (or Exception itself), excluding the class RuntimeException and all its subclasses. These exceptions cannot be ignored at the time of compilation and the programmers need to deal with the prospect of the exception that will be thrown.

Examples of Checked Exception:

IOException
SQLException

Unchecked exception

Unchecked Exceptions mainly occur for the different programming errors such as accessing a null object (NullPointerException), accessing an element of an array that is out of bounds (ArrayBoundExceptions). Unchecked Exception is direct sub Class of RuntimeException.


Exception Hierarchy



The super class for exceptions is Throwable and it contains two subclasses Error and Exception. Every class in the hierarchy suffixes with Exception, but Error does not. All the exceptions are caused by problems within software  but Error is caused by hardware problems, The above of exceptions can be divided in two categories – unchecked exceptions and checked exceptions.

Throw

Throw is used to actually throw the exception. It is used to raise exception explicitly that means it is use when a user defined exception is raised.

Throws

Throws keyword, used to declare an exception. It gives the information regarding the exception to the programmer so the programmer can provide an exception handling code. They are not interchangeable.


Try block

A try statement is used to catch exceptions that might be thrown by an executed program. Whenever, a try block is in use a statement that might throw an exception and that prevent from program crashing if any exception occurs.


Catch Block

The catch block contains a series of legal Java statements. These statements are executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose type matches that of the exception thrown.


Finally

When a try block runs till the end, and there are no exception is
Thrown then the finally block will be executed after the try block but when an exception is thrown by the try block and it caught in one of the catch blocks the finally block will execute after the catch block.

Difference between Errors and Exception

Exceptions:

An exception has two subclasses, checked and unchecked. The Exception is point out an error that may cause by the programmer.  An Exception handled at the application level
Errors:

Errors are generated to indicate errors generated by the runtime environment. Errors don't have any subclasses while, tare always unchecked. Errors can be lethal in nature and revival from Error often is not possible. Usually indicate a system error or a problem with a low-level resource. Errors should be handled at the system level.



Example of Some Checked and Unchecked Exceptions

Checked

IOException
InterruptedException      
NoSuchMethodException
ClassNotFoundException
CloneNotSupportedException
FileNotFoundException
ParseException
InstantiationException
Unchecked

NullPointerException
StackOverflowError
ArrayIndexOutOfBoundsException       
IllegalArgumentException
ExceptionInInitializerError
IllegalStateException
NumberFormatException
ClassCastException
NoClassDefFoundError



Thursday, August 15, 2013

Wrapper Class - II


Autoboxing

Autoboxing is a process when primitive data types in Java automatically converts into its corresponding wrapper class object. Like, converting an char to Character, int to an Integer or double to a Double.

Autoboxing Example :

import java.util.*;
class Autoboxing
    {
        public static void main(String args[])
            {
                Integer num=5; //Invoke Integer.valueOf()
                Double D=5.4; //Invoke Double.valueOf()
                Float F=5.0F; //Invoke Float.valueOf()
                Character ch='x'; //Character.valueOf()
                ArrayList N= new ArrayList();
                System.out.println("Integer : "+num);
                System.out.println("Double : "+D);
                System.out.println("Float : "+F);
                System.out.println("Character : "+ch);
                N.add(5);
                N.add(9);
                N.add(11);
                N.add(6);
                N.add(7);
              System.out.print("\nArrayList : ");
              System.out.print("\nArrayList : ");
                for(int i=0;i<5;i++)
                    {
                        System.out.print(N.get(i)+"  ");
                    }
            }
    }
            }
            }
    }              

Unboxing

When automatic conversion taken place for an object of a wrN.add(7)apper type to its corresponding primitive value is known as unboxing.

Unboxing Example :

public class Unboxing
    {
        public static void main(String args[])
            {
                Integer NUM=10;
                Double D=12.5;
                int num=NUM;
                double d=D;
                System.out.println("Integer : "+NUM+"  int : "+num);
                System.out.println("Double : "+D+"  double : "+d);
            }
    }
   

Friday, August 9, 2013

Wrapper Classes – I.




Java languages have eight primitive data types but primitive data types are not objects and they not belongs to any class. Often a primitive data type need to converted into a objects and wrapper wraps the around the data type to give an object effect. In some cases we cannot use primitive data type, so we need wrapper classes. For example, we need a wrapper class when we want to store number as a collection.

Data Type
Wrapper class
Uses
Remark
int
Integer
intValue()
Compare two Integer objects as numeric.
long
Long
longValue()
Returns value of Integer as  long.
float
Float
floatValue()
Returns the value of Integer as float.
double
Double
doubleValue()
Returns value of Integer as a double.
short
Short
shortValue();
Returns value of Integer as a short.
char
Character
Character CharObj = new Character(ch);
wrap primitive data type char value in an object
byte
Byte
byteValue()
Returns value of Integer as a byte.
boolean
Boolean
boolean equals(Object int_Obj)
Returns true if the Integer object is equivalent to int_Obj, or else returns false.

Parsing is to read the value of one object to convert it to another type. The parses method is used to get the primitive data type from a String 'parse' or convert strings into numbers.

Example:

parseInt(str)        Rreturns a signed decimal integer value that equivalent to String str.
parseDouble(str)  Rreturns a signed decimal double value that equivalent to String str.
parseFloat(str)     Rreturns a signed decimal Float value that equivalent to String str.
toString(int)        Rreturns a String object from an integer.

A float has 32 bits, and a double 64. doubles have higher precision than ints and floats.

Example:

import java.io.*;
class Parse_test
    {
            public static void main(String args[]) throws IOException
                {
                    BufferedReader Br=new BufferedReader(new InputStreamReader(System.in));
                    int Inum;
                    double Dnum;
                    float Fnum;
                    System.out.print("\tEnter an Integer Value : ");
                    Inum=Integer.parseInt(Br.readLine());
                    System.out.print("\tEnter an Double Value : ");
                    Dnum=Double.parseDouble(Br.readLine());
                    System.out.print("\tEnter an Float No. : ");
                    Fnum=Float.parseFloat(Br.readLine());
                    System.out.println("\n\tInteger Value : "+Inum);
                    System.out.println("\n\tDouble Value : "+Dnum);
                    System.out.println("\n\tFloat Value : "+Fnum);
                }
   }