Chapter-1 Exception Handling in Javan - Rvu
Chapter-1 Exception Handling in Javan - Rvu
Exceptions
1
• Objective:
– To know what is exception and what is exception handling
.
– To distinguish exception types: Error (fatal) vs. Exception
(non-fatal), and checked vs. uncheck exceptions .
– To declare exceptions in the method header .
– To throw exceptions out of a method .
– To write a try-catch block to handle exceptions .
– To explain how an exception is propagated .
– To rethrow exceptions in a try-catch block .
– To use the finally clause in a try-catch block .
– To know when to use exceptions .
– To declare custom exception classes .
2
Syntax Errors, Runtime Errors, and Logic Errors
• You learned that there are three categories of errors:
syntax errors, runtime errors, and logic errors.
• Syntax errors arise because the rules of the language
have not been followed.
• They are detected by the compiler.
• Runtime errors occur while the program is running if
the environment detects an operation that is
impossible to carry out.
• Logic errors occur when a program doesn't perform
the way it was intended to.
3
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
4
Catch Runtime Errors
1 import java.util.*; Run
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 } 5
• An exception (or exceptional event) is a problem that arises during
the execution of a program.
• When an Exception occurs the normal flow of the program is
disrupted and the program/Application terminates abnormally, which
is not recommended, therefore, these exceptions are to be handled.
• An exception can occur for many different reasons. Following are
some scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications or the JVM has run out of memory
• Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have failed
in some manner.
6
• An exception is an unwanted or unexpected event, which occurs
during the execution of a program i.e at run time, that disrupts
the normal flow of the program’s instructions.
• Exception:
– Exception indicates conditions that a reasonable application might try to
catch.
• Error:
– An Error indicates serious problem that a reasonable application should
not try to catch.
– Errors are the conditions which cannot get recovered by any handling
techniques
– It surely cause termination of the program abnormally.
– These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer.
– Errors belong to unchecked type and mostly occur at runtime. Some of the
examples of errors are Out of memory error or a System crash error.
7
Exception -Hierarchy
8
Exception Classes and Hierarchy
9
• All exception and errors types are sub classes of class
Throwable, which is base class of hierarchy.
12
Runtime Exceptions
RuntimeException is caused
by programming errors, such
as bad casting, accessing an
out-of-bounds array, and
numeric errors.
13
• Types of Exceptions
– There are two types of exceptions:
– Unhecked
and
– checked Exceptions
14
Checked Exceptions vs. Unchecked Exceptions
•RuntimeException, Error and their subclasses are
known as unchecked exceptions.
•All other exceptions are known as checked exceptions,
meaning that the compiler forces the programmer to
check and deal with the exceptions.
15
•Unchecked Exceptions
•Unchecked exceptions are the exceptions that are not checked at
compiled time.
•An unchecked exception is an exception that occurs at the time of
execution.
•These are also called as Runtime Exceptions.
•These include programming bugs, such as logic errors or improper
use of an API. Runtime exceptions are ignored at the time of
compilation.
•In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable. For example, a NullPointerException
is thrown if you access an object through a reference variable before
an object is assigned to it;
16
• an IndexOutOfBoundsException is thrown if
you access an element in an array outside the
bounds of the array. These are the logic errors that
should be corrected in the program.
• Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-
catch blocks, Java does not mandate you to write
code to catch unchecked exceptions.
17
Consider the following Java program. It compiles fine, but it throws
ArithmeticException when run. The compiler allows it to compile,
because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
18
Checked Exceptions
• Checked exceptions like IOException known to the compiler at compile
time while unchecked exceptions like ArrayIndexOutOfBoundException
known to the compiler at runtime. It is mostly caused by the program written
by the programmer.
• are the exceptions that are checked at compile time.
• If some code within a method throws a checked exception, then the method
must either handle the exception or it must specify the exception using
throws keyword.
• For example, consider the following Java program that opens file at location
“C:\test\a.txt” and prints the first three lines of it.
• The program doesn’t compile, because the function main() uses FileReader()
and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked
exception IOException
19
Example of checked Exception
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
20
• To fix the above program, we either need to specify list of exceptions using throws, or
we need to use try-catch block. We have used throws in the below program. Since
FileNotFoundException is a subclass of IOException, we can just specify IOException
in the throws list and make the above program compiler-error-free.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
21
Checked or Unchecked Exceptions
Unchecked
exception.
22
All exceptions are instances of classes that are
subclasses of Exception
Exception
ArrayIndexOutofBounds FileNotFoundException
NullPointerException MalformedURLException
IllegalArgumentException SocketException
etc. etc.
try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}
26
• Java try and catch
– The try statement allows you to define a block of
code to be tested for errors while it is being
executed.
– The catch statement allows you to define a block of
code to be executed, if an error occurs in the try
block.
– The try and catch keywords come in pairs:
27
• Example:
• This will generate an error, because myNumbers[10]
does not exist.
28
public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went
wrong.");
} } }
29
The finally Clause
•The finally statement lets you execute code, after try...catch,
regardless of the result
•The finally block in java is used to put important codes such as clean
up code e.g. closing the file or closing the connection.
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
} 30
Example:
public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e)
{ System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is
finished.");
} } }
31
Example:Catching Specific Type of
Exception, ArrayIndexOutOfBoundsException
public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (ArrayIndexOutOfBoundsException
e) { System.out.println("Something
went wrong.");
} finally {
System.out.println("The 'try catch' is
finished.");
} } }
32
• Note the following −
– A catch clause cannot exist without a try statement.
– It is not compulsory to have finally clauses
whenever a try/catch block is present.
– The try block cannot be present without either
catch clause or finally clause.
– Any code cannot be present in between the try,
catch, finally blocks.
33
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
34
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
35
Trace a Program Execution
try { Next statement in
statements; the method is
} executed
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
36
Trace a Program Execution
Next statement;
37
Trace a Program Execution
try {
statement1;
The exception is
handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
38
Trace a Program Execution
try {
statement1; The final block is
statement2; always executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
39
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
40
Multiple Catch Blocks
• A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
}
catch (ExceptionType2 e2) {
// Catch block
}
catch (ExceptionType3 e3) {
// Catch block }
41
• If an exception occurs in the protected code, the
exception is thrown to the first catch block in the
list.
• If the data type of the exception thrown matches
ExceptionType1, it gets caught there.
• If not, the exception passes down to the second
catch statement.
• This continues until the exception either is caught
or falls through all catches, in which case the
current method stops execution and the exception
is thrown down to the previous method on the call
stack.
42
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
43
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
44
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
45
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
46
Example: Catching Multiple Exceptions
class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}
47
Exception Classes and Hierarchy
• Multiple catches should be ordered from subclass to
superclass.
class MultipleCatchError {
public static void main(String args[]){
try {
int a = Integer.parseInt(args [0]);
int b = Integer.parseInt(args [1]);
System.out.println(a/b);
} catch (Exception ex) {
} catch (ArrayIndexOutOfBoundsException e) {
}
}
}
48
Exceptions Methods
Following is the list of important methods available in the Throwable class
50
//Example of Catching multiple Exceptions
Catching Exceptions:
Multiple catch
class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}
51
Built-in Exceptions in Java with examples
• Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java
ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not
found FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
NoSuchMethodException
It is thrown when accessing a method which is not found. 52
• NullPointerException
This exception is raised when referring to the members of
a null object. Null represents nothing
• NumberFormatException
This exception is raised when a method could not convert
a string into a numeric format.
• RuntimeException
This represents any exception which occurs during
runtime.
• StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an
index is either negative than the size of the string
53
Example // Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
54
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
55
// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
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("StringIndexOutOfBoundsException");
}
}
}
56
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
57
// Java program to demonstrate ArrayIndexOutOfBoundException
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){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
58
Throwing Exceptions
59
Throwing Exceptions
The throw Keyword
• When the program detects an error, the program can create
an instance of an appropriate exception type and throw it.
This is known as throwing an exception.
• The throw keyword in Java is used to explicitly throw an
exception from a method or any block of code. We can
throw either checked or unchecked exception.
• The throw keyword is mainly used to throw custom
exceptions.
Syntax:
throw instance
• An exception you throw is an object
60
Syntax
throw new TheException();
or
61
• You have to create an exception object in the
same way you create any other object
Example :
62
Example: Throwing Exceptions
class ThrowDemo {
public static void main(String args[]){
String input = “invalid input”;
try {
if(input.equals(“invalid input”)) {
throw new RuntimeException("throw demo");
} else {
System.out.println(input);
}
System.out.println("After throwing");
} catch (RuntimeException e) {
System.out.println("Exception caught:" + e);
}
}
}
63
Example of throwing an exception object.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
• In the above example, if the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
64
/** Set a new radius */
65
Java Exception propagation
– An exception is first thrown from the top of the
stack and if it is not caught, it drops down the call
stack to the previous method,
– If not caught there, the exception again drops down
to the previous method, and so on until they are
caught or until they reach the very bottom of the
call stack.
– This is called exception propagation.
66
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");
} }
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
} } 67
• In the above example exception occurs in m() method where it is not handled,
so it is propagated to previous n() method where it is not handled, again it is
propagated to p() method where exception is handled.
• Exception can be handled in any method in call stack either in main()
method,p() method,n() method or m() method.
68
Rule: By default, Checked Exceptions are not forwarded
in calling chain (propagated)
Program which describes that checked exceptions are not propagated
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
71
• Rules on Exceptions
• A method is required to either catch or list all exceptions it might throw
• Except for Error or RuntimeException, or their subclasses
• If a method may cause an exception to occur but does not catch it, then
it must say so using the throws keyword
Advantage of Java throws keyword
– Now Checked Exception can be propagated (forwarded in call stack).
– It provides information to the caller of the method about the
exception.
72
Note:
• In a program, if there is a chance of rising an exception then
compiler always warn us about it and compulsorily we should
handle that checked exception, Otherwise we will get compile
time error saying unreported exception XXX must be caught or
declared to be thrown. To prevent this compile time error we can
handle the exception in two ways:
– By using try catch
– By using throws keyword
• We can use throws keyword to delegate the responsibility of exception
handling to the caller (It may be a method or JVM) then caller method is
responsible to handle that exception
73
Java throws example
• Let's see the example of java throws clause which describes that
checked exceptions can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
} 74
}
Example: Method throwing an Exception
class ThrowingClass {
static void meth() throws ClassNotFoundException {
throw new ClassNotFoundException ("demo");
}
}
class ThrowsDemo {
public static void main(String args[]) {
try {
ThrowingClass.meth();
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}
75
Rule: If you are calling a method that declares an exception, you
must either caught or declare the exception.
76
Case1: You handle the exception
• In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){
System.out.println("exception handled");
}
System.out.println("normal flow...");
}
} 77
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur,
the code will be executed fine.
78
A)Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
79
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output: Runtime Exception
80
• Important points to remember about throws keyword:
– throws keyword is required only for checked exception
and usage of throws keyword for unchecked exception
is meaningless.
– throws keyword is required only to convince compiler
and usage of throws keyword does not prevent
abnormal termination of program.
– By the help of throws keyword we can provide
information to the caller of the method about the
exception
81
Difference between throw and throws in Java
• The differences between throw and throws are:
1.Point of usage
– throw keyword is used inside a function. It is used
when it is required to throw an Exception logically.
– throws keyword is in the function signature. It is
used when the function has some statements that can
lead to some exceptions
82
Example:
83
2. Number of exceptions thrown
– throw keyword is used to throw an exception explicitly. It can
throw only one exception at a time
– throws keyword can be used to declare multiple exceptions,
separated by comma. Whichever exception occurs, if matched with
the declared ones, is thrown automatically then.
// throwing multiple exceptions
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}
84
3. Syntax
– Syntax of throw keyword includes the instance of
the Exception to be thrown.
– Syntax of throws keyword includes the class names
of the Exceptions to be thrown
4. Propagation of Exceptions
– throw keyword cannot propagate checked
exceptions. It is only used to propagate the
unchecked Exceptions that are not checked using
throws keyword.
– throws keyword is used to propagate the checked
Exceptions only.
85
Eg:
void main() throws IOException
{
// Using throw for ArithmeticException
// as it is unchecked in throws
throw new ArithmeticException();
}
Eg:
void main() throws IOException
{
}
86
Declaring, Throwing, and Catching Exceptions
87
Catching Exceptions
main method { method1 { method2 {
... ... ...
try { try { try {
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) catch (Exception2 ex2) catch (Exception3 ex3)
{ { {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
88
Catch or Declare Checked Exceptions
• Java forces you to deal with checked exceptions.
• If a method declares a checked exception (i.e., an
exception other than Error or RuntimeException),
you must invoke it in a try-catch block or declare
to throw the exception in the calling method.
• For example, suppose that method p1 invokes
method p2 and p2 may throw a checked exception
(e.g., IOException), you have to write the code as
shown in (a) or (b).
89
Eg: void p1() throws IOException {
void p1() {
try { p2();
p2();
} }
catch (IOException ex) {
...
}
}
90
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
91
When to Throw Exceptions
• An exception occurs in a method. If you want
the exception to be processed by its caller, you
should create an exception object and throw it.
• If you can handle the exception in the method
where it occurs, there is no need to throw it.
92
When to Use Exceptions
•When should you use the try-catch block in the code? You should
use it to deal with unexpected error conditions. Do not use it to deal
with simple, expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
93
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
94
Creating Custom Exception Classes
96
• Steps to follow
– Create a class that extends the RuntimeException or the
Exception class
Example
class HateStringExp extends RuntimeException {
97
class TestHateString {
public static void main(String args[]) {
String input = "invalid input";
try {
if (input.equals("invalid input")) {
throw new HateStringExp();
}
System.out.println("Accept string.");
} catch (HateStringExp e) {
System.out.println("Hate string!”);
}
}
}
98
class InvalidAgeException extends Excepti
on{
InvalidAgeException(String s){
super(s);
}
}
99
class TestCustomException1{
static void validate(int age)throws Inval
idAgeException{
if(age<18)
throw new InvalidAgeException("not valid
");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
100
try{
validate(13);
}catch(Exception m)
{System.out.println("Exception occured: "
+m);}
System.out.println("rest of the code
...");
}
}
101