Exercise – 9 (User defined Exception)
a) Write a JAVA program for creation of Illustrating throw
Java Source Code
class ThrowEx
static void fun()
try
throw new NullPointerException("demo");
catch(NullPointerException e)
System.out.println("......catch of fun() method.......");
throw e; // rethrowing the exception
public static void main(String args[])
try
fun();
catch(NullPointerException e)
{
System.out.println(".......catch of main() method......");
Output
b) Write a JAVA program for creation of Illustrating finally
Java Source Code
class FinallyBlockEx{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
catch(ArithmeticException e){
System.out.println("....denominator must not be zero.....");
finally{
System.out.println(".....finally block is always executed.....");
System.out.println("........rest of the code...");
Output
c) Write a JAVA program for creation of Java Built-in Exceptions
IOException
import java.io.*;
class IOExceptionEx {
public static void main(String args[])throws IOException
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
f.close();
Output
InterruptedException
class InterruptedExceptionEx{
public static void main(String args[]) throws InterruptedException
Thread t = new Thread();
for (int i=1;i<5 ;i++ )
System.out.println("......Main Thread...."+i);
Thread.sleep(1000);
Output
StringIndexOutOfBoundsException
class StringIndexOutOfBoundEx {
public static void main(String args[])
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
catch (StringIndexOutOfBoundsException e) {
System.out.println("....Accessing character does not exist.....");
Output
d) Write a JAVA program for creation of User Defined Exception
Java Source Code
//user defined exception
class VotingException extends Exception {
VotingException() {
System.out.println("..........Not eligible for voiting....");
}//userdifined exception
class VotingTest { //bussiness logic class
static void displayEligibility(int age)throws VotingException {
if(age<19)
throw new VotingException();
System.out.println("............eligible for voting.........");
class UserDefinedException {
public static void main(String args[]) {
int age=Integer.parseInt(args[0]);
try {
VotingTest.displayEligibility(age);
catch(VotingException e)
}
Output