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

Core Java - Exception Handling

1. throws is used to declare exceptions in a method signature while throw is used to explicitly throw an exception. 2. Syntax wise, throw is followed by an instance while throws is followed by exception class names. 3. throw is used inside a method body to throw an exception, throws is used in a method signature. 4. throws can declare multiple exceptions in a method signature separated by commas.

Uploaded by

Paresh Sonparote
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Core Java - Exception Handling

1. throws is used to declare exceptions in a method signature while throw is used to explicitly throw an exception. 2. Syntax wise, throw is followed by an instance while throws is followed by exception class names. 3. throw is used inside a method body to throw an exception, throws is used in a method signature. 4. throws can declare multiple exceptions in a method signature separated by commas.

Uploaded by

Paresh Sonparote
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Difference between throw and throws in java

SNO throws throw


1 Throws clause is used to declare an exception, which means it works similar to the try- On the other hand throw keyword is used to throw an exception explicitly.
catch block.
2 If we see syntax wise then, throws is followed by exception class names. throw is followed by an instance of Exception class.
Example:
throws ArithmeticException; Example:
throw new ArithmeticException("Arithmetic Exception");

3 throws keyword is used in method signature to declare the exceptions that can occur in Throw keyword is used in the method body to throw an exception.
the statements present in the method.
Example: Example:
//Declaring arithmetic exception using throws void myMethod() {
void sample() throws ArithmeticException{ try {
//Statements //throwing arithmetic exception using throw
} throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}

4 You can handle multiple exceptions by declaring them using throws keyword. You can throw one exception at a time.
Example:
//Declaring multiple exceptions using throws Example:
void myMethod() throws ArithmeticException, NullPointerException{ void myMethod() {
//Statements where exception might occur //Throwing single exception using throw
} throw new ArithmeticException("An integer should not be divided by zero!!");
}

5 Complete Program: Complete Program:

public class Example1{ public class Example1{


int division(int a, int b) throws ArithmeticException{ void checkAge(int age){
int t = a/b; if(age<18)
return t; throw new ArithmeticException("Not Eligible for voting");
} else
public static void main(String args[]){ System.out.println("Eligible for voting");
Example1 obj = new Example1(); }
try{ public static void main(String args[]){
System.out.println(obj.division(15,0)); Example1 obj = new Example1();
} obj.checkAge(13);
catch(ArithmeticException e){ System.out.println("End Of Program");
System.out.println("You shouldn't divide number by zero"); }
} }
}
} Output:

Output: Exception in thread "main" java.lang.ArithmeticException:


Not Eligible for voting
You shouldn't divide number by zero at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)
Difference between throw and throws in java

1. Point of Usage.

throw keyword is used inside a function. It is used when it is required to throw an Exception logically.

void Demo() throws ArithmeticException, NullPointerException


{
// Statements where exceptions might occur.
throw new ArithmeticException();
}

throws keyword is in the function signature. It is used when the function has some statements that can lead to some
exceptions.

void Demo()
{
// Statements where exceptions might occur.
}

2. Number of exceptions thrown.

throw keyword is used to throw an exception explicitly. It can throw only one exception at a time.

// throwing only an IOException


throw new IOException();

throws keyword can be used to declare multiple exceptions, separated by comma. Whichever exception occurs, if matched
with the declared ones, is thrown automatically then.

// throwing multiple exceptions


void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}

3. Syntax.

Syntax of throw keyword includes the instance of the Exception to be thrown.


// throwing instance of IOException
throw new IOException();

Syntax of throws keyword includes the class names of the Exceptions to be thrown.
// throwing multiple exceptions by class names
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}

4. Propagation of Exceptions.

throw keyword cannot propagate checked exceptions. It is only used to propagate the unchecked Exceptions that are not
checked using throws keyword.

void main() throws IOException


{
// Using throw for ArithmeticException
// as it is unchecked in throws
throw new ArithmeticException();
}

throws keyword is used to propagate the checked Exceptions only.


void main() throws IOException
{
}
5. Example.

throw:
public class GFG {
public static void main(String[] args)
{
// Use of unchecked Exception
try
{
// double x=3/0;
throw new ArithmeticException();
}

catch (ArithmeticException e)
{
e.printStackTrace();
}
}
}

Output:

java.lang.ArithmeticException: / by zero
at UseOfThrow.main(UseOfThrow.java:8)

throws:
import java.io.IOException;

public class UseOfThrowAndThrows {

public static void main(String[] args)throws IOException


{
----
----
----
}
}

Output:

Exception in thread "main" java.io.IOException


at UseOfThrowAndThrows.main(UseOfThrow.java:7)

THROW THROWS

throws keyword is used to declare one or more exceptions, separated by

commas.
throw keyword is used to throw an exception explicitly.

Only single exception is thrown by using throw. Multiple exceptions can be thrown by using throws.

throw keyword is used within the method. throws keyword is used with the method signature.

Syntax wise throw keyword is followed by the instance variable. Syntax wise throws keyword is followed by exception class names.

Checked exception cannot be propagated using throw only. Unchecked For the propagation checked exception must use throws keyword followed

exception can be propagated using throw. by specific exception class name.


1. throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.
2. If we see syntax wise then throw is followed by an instance variable and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
For example

throw

throw new Exception("You have some exception")


throw new IOException("Connection failed!!")

throws

public int myMethod() throws IOException, ArithmeticException, NullPointerException {}

4. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws
IOException,SQLException.
5. checked exceptions can not be propagated with throw only because it is explicitly used to throw an particular exception. checked exception can be
propagated with throws.

Exception propagation: An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which
calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these
methods catches the exception.

Difference between throw and throws


throw throws

throws keyword is used to declare an exception possible during its


throw keyword is used to throw an exception explicitly.
execution.

throw keyword is followed by an instance of Throwable class or one throws keyword is followed by one or more Exception class names
of its sub-classes. separated by commas.

throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration).

We can declare multiple exceptions (separated by commas) using


We cannot throw multiple exceptions using throw keyword.
throws keyword.
Exception Handling in Java.

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

An Exception means abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

The core advantage of exception handling is to maintain the normal flow of the application.

Example:
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.
A hierarchy of Java Exception classes are given below diagram.
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked.


Here, an error is considered as the unchecked exception.
According to Oracle, there are three types of exceptions:

1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

try:
The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.

catch:
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally:
The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.

throw:
The "throw" keyword is used to throw an exception.

throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
Built-in Exceptions / Exceptions Types

Built-in exceptions are the exceptions which are available in Java libraries. Below is the list of important built-in exceptions in Java.

Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of the string

Note That

Note the following −

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses whenever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Any code cannot be present in between the try, catch, finally blocks.
Short Summary of Exception Handling

An Exception is a run-time error which interrupts the normal flow of program execution.Disruption during the execution of the program is referred as error or exception.

Errors are classified into two categories


Compile time errors – Syntax errors, Semantic errors
Runtime errors- Exception

A robust program should handle all exceptions and continue with its normal flow of program execution. Java provides an inbuilt exceptional handling method

Exception Handler is a set of code that handles an exception. Exceptions can be handled in Java using try & catch.

Try block: Normal code goes on this block.

Catch block: If there is error in normal code, then it will go into this block

You might also like