Examples of Built-in Exception:
1) Arithmetic exception
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
}
catch(ArithmeticException e) {
[Link] ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
2) NullPointer Exception
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
[Link]([Link](0));
} catch(NullPointerException e) {
[Link]("NullPointerException..");
}
}
}
Output:
NullPointerException..
3) StringIndexOutOfBound Exception
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element
[Link](c);
}
catch(StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
4) NumberFormat Exception
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = [Link] ("akki") ;
[Link](num);
} catch(NumberFormatException e) {
[Link]("Number format exception");
}
}
}
Output:
Number format exception
5) ArrayIndexOutOfBounds Exception
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
[Link] ("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds