Code for InvalidAgeException:
Code for VoterAppn using throws :
Output:
package com.ca;
public class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
}
public InvalidAgeException(String message )
{
super(message);
}
public void checkAge( int age ) throws InvalidAgeException
{
try
{
if(age >= 18)
{
System.out.println("You are eligible for votting \n" + "Please fil the remaining details" );
}
else
{
throw new InvalidAgeException(" Invalid Age ");
}
}
catch(InvalidAgeException e )
{
throw e; // re-throwing exception
}
}
}
public class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
}
public InvalidAgeException(String message )
{
super(message);
}
public void checkAge( int age ) throws InvalidAgeException
{
try
{
if(age >= 18)
{
System.out.println("You are eligible for votting \n" + "Please fil the remaining details" );
}
else
{
throw new InvalidAgeException(" Invalid Age ");
}
}
catch(InvalidAgeException e )
{
throw e; // re-throwing exception
}
}
}
package com.gov.tel;
import java.util.Scanner;
import com.ca.InvalidAgeException;
public class VoterAppn {
public static void main(String[] args) throws InvalidAgeException
{
Scanner scan = new Scanner( System.in );
System.out.println(" Enter your age: ");
int age = scan.nextInt();
InvalidAgeException iae = new InvalidAgeException();
iae.checkAge(age);
}
}
import java.util.Scanner;
import com.ca.InvalidAgeException;
public class VoterAppn {
public static void main(String[] args) throws InvalidAgeException
{
Scanner scan = new Scanner( System.in );
System.out.println(" Enter your age: ");
int age = scan.nextInt();
InvalidAgeException iae = new InvalidAgeException();
iae.checkAge(age);
}
}
Output:
Code for VoterAppn without using throws :
package com.gov.tel;
import java.util.Scanner;
import com.ca.InvalidAgeException;
public class VoterAppn {
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println(" Enter your age: ");
int age = scan.nextInt();
InvalidAgeException iae = new InvalidAgeException();
try
{
iae.checkAge(age);
}
catch(InvalidAgeException e )
{
System.out.println(" Your age is not sufficient for voting");
}
}
}
import java.util.Scanner;
import com.ca.InvalidAgeException;
public class VoterAppn {
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println(" Enter your age: ");
int age = scan.nextInt();
InvalidAgeException iae = new InvalidAgeException();
try
{
iae.checkAge(age);
}
catch(InvalidAgeException e )
{
System.out.println(" Your age is not sufficient for voting");
}
}
}