In this article throw and throws in java we give the information about “try” keyword is used to specify a block where we keep the exception code. “catch” block is used to handle the exception.
throw and throws in java:
Exception Handling
In Java, exception is handled by 5 keywords.
- Try
- Catch
- Finally
- Throw
- Throws
Try –
- “try” keyword is used to specify a block where we keep the exception code.
- There must be a catch block or finally block at the end of this block. This means that we cannot use the try block alone.
- If it contains both catch and finally then their sequence should be try-catch-finally. Because if their order is wrong then compile-time error will occur.
- The code inside the try block should always be inside curly braces. Otherwise a compile-time error will occur.
Its syntax –
Try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{
// handling code
}
Example:
Catch –
- “catch” block is used to handle the exception.
- It should always be used after try block. This means that we cannot use catch alone.
- This block takes one argument. This argument should either be of type Throwable or its sub-class.
- The code inside the catch block should always be inside curly braces. Otherwise a compile-time error will occur.
Its syntax –
try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
Finally –
- “finally” block is used to execute important codes of the program. Such as – closing the database connection, closing file resources etc.
- It is always used with try-catch block.
- There can be 2 combinations with finally. One try-finally and the other try-catch-finally.
- The finally block is always executed, whether the exception has been handled or not.
- It executes after try and catch block.
Its syntax –
try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
//always execute
}
Example:
import java.io.FileInputStream;
class TryCatchFin
{
public static void main(String [] args)
{
try
{
int a=100,b=0,c;
c=a/b;
System.out.println(c);
}
catch(Exception e) // you cannot divided by zero
{
System.out.println(e);
}
finally
{
System.out.println(“I am in finally block.”);
}
System.out.println(“Good bye!”);
}
}
Output:
Compile: javac TryCatchFin.java
Run: java TryCatchFin
java.lang.ArithmeticException: / by zero
I am in finally block.
Good bye!
Rules for finally block:
- We can use multiple catch blocks with one try block but we can use only single finally block with one try block.
- The statement present in the finally block execute even if the try block contains control transfer statements (that is jump statements) like return, break or continue.
- The possibilities that disturbs the execution of finally block are:
- Using of the System.exit() method
- causing a fatal error that causes the process a abort.
- Due to an execution arising in the finally block
- The death of a tread.
throw and throws in java:
Throw –
- It is used to throw exception.
- It is used with both checked and unchecked exceptions.
- Generally, throw keyword is used to throw a user-defined exception.
Syntax:-
throw new Throwable_subclass;
Important Points:
- In try-catch, the main method creates the object of the exception and also handles it.
- In throw we do not create an object of exception from the main method or any other method.
- throw keyword calls a programmer created exception.
- We will not use throw keyword for pre defined exception. (like ArithmeticException etc.)
- We will use throw keyword for user defined exception.
- We use throw keyword inside the method.
- Throw keyword is mostly used unchecked exceptions.
- After throw keyword we do not provide any statement or statements.
//Program:
import java.util.Scanner;
class AgeException extends RuntimeException
{
AgeException(String msg) // parameterized constructor
{
super(msg); // call to default exception handler
}
}
class voting
{
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);
System.out.print(“Enter the age: “);
int age =s.nextInt();
try
{
if(age<18)
{
throw new AgeException(“You are not eligible for voting.”);
// using throw you create a manual object and pass to the JVM
// System.out.println(“Hello!”); -> Error Occur
}
else
{
System.out.println(“You can vote successfuly”);
}
}
catch(AgeException e)
{
e.printStackTrace();
}
System.out.println(“Have a nice Day!”);
}
}
Output:
Compile: javac voting.java
Run: java voting
Enter the age: 30
You can vote successfuly
Have a nice Day!
Compile: javac voting.java
Run: java voting
Enter the age: 15
AgeException: You are not eligible for voting.
at voting.main(voting.java:20)
Have a nice Day!
Throws –
- Throws keyword is used to declare exception.
- It is generally used to handle checked exceptions.
- If you do not want to handle the program with try and catch block then you can handle it with throws.
- throws keyword is used to declare an exception. it gives an information to the caller method that there may occur an exception so it is better for the caller method to provide the exception handling code so that normal flow can be maintained.
Syntax:-
return_type method_name() throws exception_class_name
{
//method code
}
Throws Example:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
class ReadWrite
{
void readFile() throws FileNotFoundException
{
FileInputStream fis = new FileInputStream(“d:/pqr.txt”);
}
void saveFile() throws FileNotFoundException
{
String text = “This is throws example file”;
FileOutputStream fos=new FileOutputStream(“d:/lmn.txt”);
}
}
class textThrows
{
public static void main(String [] args)
{
ReadWrite rw = new ReadWrite();
try
{
rw.readFile();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println(“Have a nice day!”);
try
{
rw.saveFile();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Output: –
Compile: javac textThrows.java
Run: java textThrows
java.io.FileNotFoundException: d:\pqr.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at ReadWrite.readFile(textThrows.java:8)
at textThrows.main(textThrows.java:23)
Have a nice day!
Difference between throw and throws:
Sr. No. | throw exception | throws exception |
1 | throw keyword is used to create an exception object manually that is by programmer. (otherwise by default method is responsible to create exception object) | throws keyword is used to declare the exception i.e. it indicate the caller method that given type of exception can occur so you have to handle it while calling. |
2 | throw keyword is mainly used for runtime exceptions or unchecked exceptions. | throws keyword is mainly used for compile time exceptions or checked exceptions. |
3 | In case of throw keyword we can throw only single exception. | In case of throws keyword we can declare multiple exceptions i.e. void readFile() throws FileNotFoundException, NullPointerException, etc |
4 | throw keyword is used within the method. | throws keyword is used with method signature |
5 | throw keyword is followed by new instance. | throws keyword is followed by class. |
6 | We cannot write any statement after throw keyword and thus it can be used to break the statement. | throws keyword does not have any such rules. |
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining