Java Throw and Throws Keyword
Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code recovery and debugging simpler.
The notice that comes with the exception contains a description of the error. These anomalies could be caused by user inputs, the server, etc.
Java's throw keyword allows us to throw either verified or unchecked exceptions. It mostly serves as a custom exception thrower. Custom exceptions will be covered later in this section. Additionally, we can use the throw keyword to specifically throw an exception and establish our own set of circumstances. For instance, dividing a number by another number may result in the throwing of an ArithmeticException.
Syntax of Throw keyword in Java:
toss Instance, that is.
Examples of Throw Keyword
Example 1: Throwing Unchecked Exception
public class TestTh1 {
//function to determine whether or whether a person is entitled to vote
public static void valid (int years) {
if(years<18) {
//Mathematical exception if ineligible to vote
throw new ArthExcp ("One is not elligible to cast a ballot");
}
else {
System.out.println("One can eligible to vote");
}
}
//main method
public static void main (String s []) {
//function is called
Valid(15);
System.out.println("rest of the code...");
}
}
Output:
One is not eligible to cast a ballot
An unchecked exception is thrown by the code above. Like checked exceptions, user defined exceptions can also be thrown.
NOTE: A method must handle or declare an unchecked exception it throws in the throws clause.
If a checked exception is thrown using the throw keyword, it must be handled using a catch block or declared in the method's throws declaration.
Example 2: Throwing Checked Exception
Any other exceptions that belong to the Throwable class are checked exceptions.
TestThrow2.java
import java.io. *;
public class TestTh2 {
// function to determine whether or whether a person is entitled to vote
public static void med () throws FileNotFoundExcp {
FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
BuffReader fileInput = new BuffReader(file);
throw new FileNotFoundException ();
}
//main method
public static void main (String s[]){
try
{
med ();
}
catch (FileNotFoundExcp e)
{
e. printStackTra ();
}
System.out.println("rest of the code...");
}
}
Output:
FileNotFoundException
rest of the code...
Example 3: Throwing User-defined Exception
TestThrow3.java
// class depicts a custom exception
class UserDefinedException extends Exception
{
public UserDefinedException (String str)
{
// calling the parent's function Object () {[native code]} exception
super(str);
}
}
// Class that references MyException above
public class TestTh3
{
public static void main (String s[])
{
{
// Print the message from the object MyException
System.out.println(ude. getMessage ());
}
}
}
Output:
This is user-defined exception
the exception caught
Throws Keyword in Java
Declaring an exception in Java requires the throws keyword. The programmer is informed that an exception might happen.
The primary purpose of exception handling is to manage checked exceptions. Programmers are to blame for any unchecked exceptions, such as NullPointerException, because they failed to examine the code before it was utilised.
Syntax of Java throws:
return_type method_name () throws exception_class_name
{
//method code
}
Which exception should be declared?
Ans: merely checked the exception, because:
Unchecked exception: within our power to fix our code.
error: not within our power. For instance, if a VirtualMachineError or StackOverflowError happens, nothing can be done.
Advantages of Java Throws Keyword
Checked Exceptions can now spread (forwarded in call stack).It informs the method's caller with details on the exception.
Examples of Java Throws Keyword
Let's look at an example of a Java throws clause that explains how the throws keyword can propagate checked exceptions.
Testth1.java
import java.io. IOException.
class Testth1{
void mn () throwsIOException {
throw new IOException ("error of the device”) ;//exception is checked
}
void mm () throwsIOException {
mn ();
}
void pp() {
try {
mm ();
} catch (Exception e) {System.out.println("exception handled");}
}
public static void main (String s[]){
Testth1 ob=new Testth1();
ob. pp ();
System.out.println("flow is normal...");
}
}
Output:
exception handled
flow is normal...
Rule: If a method is being called that declares an exception, the exception must either be caught or declared.
There are two cases:
Case 1: Deal with Exception Try-catch block usage
Regardless of whether the exception happens during the program or not, if it is handled, the function will execute without problem.
Testthrows2.java
import java.io. *;
class Mm {
void med () throwsIOException {
throw new IOException ("error of devie");
}
}
public class Testth2{
public static void main(String s[]){
try{
Mm m=new Mm ();
m.med ();
}catch(Exception e) {System.out.println("exception is handled");}
System.out.println("flow is normal...");
}
}
Output:
exception is handled
flow is normal...
Case 2: Declare Exception
- If the exception is declared, the function will run without a problem if it doesn't happen.
Let's look at some samples for each case.
a) If the exception doesn't happen
Testthrows3.java
import java.io. *;
class Mm {
void med () throwsIOException {
System.out.println("operation performed by the device is done");
}
}
class Testth3{
public static void main (String s []) throwsIOException {//exception is declared
M m=new Mm ();
Mm.med ();
System.out.println("flow is normal...");
}
}
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4.java
import java.io. *;
class Mm {
void med () throwsIOException {
throw new IOException ("error of the device");
}
}
class Testthrows4{
public static void main (String s[])throws IOException {//exception is declared
Mm m=new Mm ();
m.med ();
System.out.println("flow is normal...");
}
}
Output:
Exception in Thread
Unchecked Exceptions:
Rather than being checked during compilation, these are checked at runtime.
Think about the ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException, etc. as an example.
Checked exceptions are those that are reviewed during compilation. Examples include IOException, InterruptedException, etc.
Unchecked exceptions are something we rarely must deal with. The reason for this is that programming errors could result in unchecked exceptions. Furthermore, a good strategy is to correct them rather than handle them.
Differences between Throw and Throws:
In everyday speech, the sole distinction between "throw" and "throws" is tenses. However, these two are significantly different from one another and are employed for a variety of activities in the computer language Java. The Java language's exception handling uses the terms throw and throws.
While throws is used in the method signature to indicate that this method may throw one of the stated type exceptions, throw is used to explicitly throw an exception from a method or any other block of code. Throw and throws are both concepts related to handling exceptions.
The "Throw" keyword is used to pass a manually constructed exception instance to the JVM, whereas the "throws" keyword is used to pass the burden of handling an exception that occurred in a method to the calling method. Throw and throws are two concepts for handling exceptions, with throw throwing the exception directly from a function or block of code and throws being used in a method's signature.
Point of Use
- When it is necessary to logically throw an exception, it is utilized. The function signature makes use of the throws keyword. When a function contains statements that could result in an exception, it is used.
Second Exceptions Thrown
- When the throw keyword is used, an exception is explicitly thrown. You can only make one exception at once. Then, if an exception occurs that matches one of the listed ones, it is thrown right away.
Syntax
- The syntax of the throw keyword includes the instance of the exception that will be thrown. The instance variable comes after throw in the syntax. The syntax of the throws keyword includes the class names of the exceptions that will be thrown. The names of the exception classes are immediately followed by the syntactic term throws.
Exception
- The Dissemination of Exceptions The throw keyword cannot propagate checked exceptions. The throws keyword only propagates unchecked exceptions that are not checked. The throws keyword can only propagate checked Exceptions.
Example:
TestThrowAndThrows.java
public class TestThrowAndThrows
{
// the creation of a user-defined method that throws an ArithmeticException
static void method () throws ArithmeticException
{
System.out.println("Inside the med ()");
throw new ArithmeticException ("throwing ArithmeticException");
}
//main method
public static void main (String s[])
{
try
{
Med();
}
Catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output:
Exception handled