uUNIT-III OOPC JAVA
uUNIT-III OOPC JAVA
16. }
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
System.out.println("hi");
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(“divide by zero “);
}
System.out.println("rest of the code");
} }
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
System.out.println("hi");
int data=50/0; //may throw exception
}
//handling the exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }
Java Catch Multiple Exceptions
try block can be followed by one or more catch blocks.
Each catch block must contain a different exception handler.
So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Before Java 7, we had to catch only one exception type in each catch block.
So, whenever we needed to handle more than one specific exception but take some
action for all exceptions,
we had to have more than one catch block containing the same code.
Starting from Java 7.0, it is possible for a single catch block to catch multiple
exceptions by separating each with | (pipe symbol) in the catch block.
The Java throw keyword is used to throw an exception explicitly.
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.
Creating our own Exception is known as custom exception or user-
defined exception. Basically, Java custom exceptions are used to
customize the exception according to user need.
To indicate that something goes wrong, we use throw keyword.
The throw keyword is used to throw an exception instance
explicitly from a try block to corresponding catch block. That
means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters
the throw keyword, it stops the execution of try block and jump to the
corresponding catch block.
}
}
What is the difference between throw and
throws?
throw throws
It is used in method definition, to
It is used to create a new
declare that a risky method is
Exception object and throw it
being called.
Using throw keyword you can Using throws keyword you can
declare only one Exception at a declare multiple exception at a
time time.
Example: Example:
throw new IOException(“can not throws IOException,
open connection”); ArrayIndexBoundException;