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

Java Throw Keyword

Java Throw Keyword
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Throw Keyword

Java Throw Keyword
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Java throw keyword

S.Kavitha
Head & Assistant Professor
Department of Computer Science
Sri Sarada Niketan College of Science for
Women,Karur.
• The Java throw keyword is used to throw an
exception explicitly.
• We specify the exception object which is to be
thrown. The Exception has some message
with it that provides the error description.
These exceptions may be related to user
inputs, server, etc.
• We can throw either checked or unchecked
exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
The syntax of the Java throw keyword is given
below.
• throw new exception_class("error message");
Let's see the example of throw IOException.
• throw new IOException("sorry device error");
Java throw keyword Example
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
output
Java throws keyword

• he 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 the normal flow of the program 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 checking the code
before it being used.
Syntax of Java throws
return_type method_name() throws exception_
class_name{
//method code
}
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...");
}
Output:
exception handled
normal flow...

You might also like