0% found this document useful (0 votes)
18 views

2 - Exception Handling

Uploaded by

Neenu Prasannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

2 - Exception Handling

Uploaded by

Neenu Prasannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Exception Handling

– ....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java finally block

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Java throw keyword

• The Java throw keyword is used to explicitly


throw an exception.
• We can throw either checked or uncheked
exception in java by throw keyword. The
throw keyword is mainly used to throw
custom exception. We will see custom
exceptions later.
• The syntax of java throw keyword is given
below.
• throw exception;
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...");
}
}
Java throws keyword

The Java throws keyword is used to declare an exception. It


gives an information to the programmer that there may
occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow
can be maintained.
Exception Handling is mainly used to handle the checked
exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}

You might also like