ArithmeticException:
- This exception class is belongs to lang package.
- It occurs when we divide any number with zero value.
import java.util.Scanner ;
class ExceptionDemo
{
public static void main(String[] args)
{
int a,b,c;
System.out.println("Enter two integers :");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
c = a/b;
System.out.println("Result : "+c);
System.out.println("Continue.....");
}
}
InputMismatchException:
- This exception class is belongs the java.util package
- Scanner class is used to read input from the user.
- Above exception raised when it read invalid input from the user.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println(“Enter 2 numbers : “);
int a = scan.nextInt();
int b = scan.nextInt();
int c = a+b;
System.out.println(“Sum : “ + c);
}
}
NumberFormatException:
- This exception class is belongs to lang package.
- This will occur when we perform invalid data conversions.
class Test
{
public static void main(String[] args)
{
String s = "java";
byte b = Byte.parseByte(s); //Exception : Invalid data conversion
}
}
ArrayIndexOutOfBoundsException: Occurs while accessing an element which is out of bounds.
class Test
{
public static void main(String[] args)
{
int arr[ ] = {10,20,30,40,50};
int len = arr.length;
System.out.println("Length is : " + len);
System.out.println("Last element : " + arr[len-1]);
System.out.println("Out of array : " + arr[len]);
}
}
NullPointerException: Occurs while accessing the functionality of object with Null pointer.
class ExceptionDemo
{
static ExceptionDemo obj1 = new ExceptionDemo();
static ExceptionDemo obj2 ;
public static void main(String[] args)
{
obj1.test();
obj2.test(); // Exception : Accessing Object functionality using NULL pointer
}
void test(){
System.out.println("Testing.....");
}
}