0% found this document useful (0 votes)
56 views11 pages

Throw Throws Throwable KEY WORD

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. We will discuss custom exceptions later in this section.

Uploaded by

sbhacker000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views11 pages

Throw Throws Throwable KEY WORD

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. We will discuss custom exceptions later in this section.

Uploaded by

sbhacker000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

THROW, THROWS AND THROWABLE – KEYWORDS IN JAVA


 THROW IN JAVA :
Throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can
throw an exception from any method or block. But, that exception must be of type java.lang.Throwableclass
or it’s sub classes.
• Below example shows how to throw an exception using throw keyword.
• Java throw example
void m()
{
throw new ArithmeticException("sorry");
}
The syntax for using throw keyword is,
• throw InstanceOfThrowableType;
where, InstanceOfThrowableType must be an object of type Throwable or subclass of Throwable.
Such explicitly thrown exception must be handled some where in the program, otherwise program will
be terminated.
FOR EXAMPLE,
public class ExceptionHandling
{
public static void main(String[] args)
{
methodWithThrow();
}
static void methodWithThrow()
{
try
{
NumberFormatException ex = new NumberFormatException(); //Creating an object to NumberFormatException explicitly
throw ex; //throwing NumberFormatException object explicitly using throw keyword
}
catch(NumberFormatException ex)
{
System.out.println("explicitly thrown NumberFormatException object will be caught here");
}
}
}
• It is not compulsory that explicitly thrown exception must be handled by immediately following
try-catch block. It can be handled by any one of it’s enclosing try-catch blocks.
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
methodWithThrow();
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException object thrown in methodWithThrow() method will be handled here");
}
}
1
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

static void methodWithThrow()


{
try
{
NumberFormatException ex = new NumberFormatException("This is an object of NumberFormatException");
throw ex; //throwing NumberFormatException object explicitly using throw keyword
}
catch(ArithmeticException ex)
{
System.out.println("Explicitly thrown NumberFormatException object will not be caught here");
}
}
}
 RE-THROWING AN EXCEPTION :
We all know that exceptions occurred in the try block are caught in catch block. Thus caught exceptions can
be re-thrown using throw keyword.
• Re-thrown exception must be handled some where in the program, otherwise program will terminate
abruptly. For example,
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
methodWithThrow();
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException Re-thrown in methodWithThrow() method will be handled here");
}
}
static void methodWithThrow()
{
try
{
String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is caught here");
throw ex; //Re-throwing NullPointerException
}
}
}

2
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

 THROWS IN JAVA :
throws is also a keyword in java which is used in the method signature to indicate that this method may throw
mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-
catch blocks or using throws keyword. If a method is capable of throwing an exception that it could not
handle, then it should specify that exception using throws keyword. It helps the callers of that method
in handling that exception.
• Below is the syntax for using throws keyword.
return_type method_name(parameter_list) throws exception_list
{
//some statements
}
• Below is the example which shows how to use throws keyword.
class ThrowsExample
{
void methodOne() throws SQLException
{
//This method may throw SQLException
}
void methodTwo() throws IOException
{
//This method may throw IOException
}
void methodThree() throws ClassNotFoundException
{
//This method may throw ClassNotFoundException
}
}
• THROWING AN EXCEPTION :
We all know that Throwable class is super class for all types of errors and exceptions.
An object to this Throwable class or it’s sub classes can be created in two ways.
• First one is using an argument of catch block. In this way, Throwable object or object to it’s sub classes
is implicitly created and thrown by java run time system.
• Second one is using new operator. In this way, Throwable object or object to it’s sub classes is explicitly
created and thrown by the code.
An object to Throwable or to it’s sub classes can be explicitly created and thrown by using throw keyword.

• JAVA THROW AND THROWS EXAMPLE


void m()throws ArithmeticException
{
throw new ArithmeticException("sorry");
}

3
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

• Multiple exceptions can be declared using throws keyword separated


by commas.
public class ExceptionHandling
{
static void methodWithThrows() throws NumberFormatException, NullPointerException
{
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
}
public static void main(String[] args)
{
try
{
methodWithThrows();
}
catch(Exception ex)
{
System.out.println("This block can handle all types of exceptions");
}
}
}
• THE MAIN USE OF THROWS KEYWORD IN JAVA IS THAT AN
EXCEPTION CAN BE PROPAGATED THROUGH METHOD CALLS.
public class ExceptionHandling
{
static void methodOne() throws NumberFormatException
{
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
}
static void methodTwo() throws NumberFormatException
{
methodOne(); //NumberFormatException is propagated here
}
static void methodThree() throws NumberFormatException
{
methodTwo(); //NumberFormatException is propagated here
}
public static void main(String[] args)
{
try
{
methodThree();
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException will be caught here");
} } }
4
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

• EVEN CONSTRUCTOR CAN USE THROWS KEYWORD.FOR THIS,


OBJECT CREATION STATEMENT MUST BE ENCLOSED IN TRY-
CATCH BLOCKS.
class A
{
int i;
public A(String s) throws NumberFormatException
{
i = Integer.parseInt(s); //This statement throws NumberFormatException
}
}
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
A a = new A(("abc"); //Object creation statement enclosed in try-catch block
}
catch (NumberFormatException ex)
{
System.out.println(“NumberFormatException will be caught here”);
}
}
}
• WHEN A METHOD IS THROWING UNCHECKED TYPE OF EXCEPTIONS, THEN
YOU NEED NOT TO MENTION IT USING THROWS KEYWORD. BUT FOR A
METHOD THROWING CHECKED TYPE OF EXCEPTIONS, YOU MUST DECLARE
IT WITH THROWS KEYWORD OR ENCLOSE THE STATEMENT WHICH IS
THROWING AN EXCEPTION IN TRY-CATCH BLOCK.
public class ExceptionHandling
{
//method throwing Unchecked Exception declared without throws clause
static void methodThrowingUncheckedException()
{
int i = Integer.parseInt("abc");
//Above statement throws NumberFormatException which is unchecked type of exception
}
//method throwing checked Exception declared with throws clause

static void methodThrowingCheckedException() throws ClassNotFoundException


{
Class.forName("AnyClassName");
//Above statement throws ClassNotFoundException which is checked type of exception
}

5
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

public static void main(String[] args)


{
try
{
methodThrowingUncheckedException();
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException will be caught here");
}
try
{
methodThrowingCheckedException();
}
catch (ClassNotFoundException e)
{
System.out.println("ClassNotFoundException will be caught here");
}
}
}
 THROWABLE IN JAVA :
Throwable is a super class for all types of errors and exceptions in java. This class is a member
of java.langpackage. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by
the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to
create your own customized exceptions, then your class must extend this class.
• Below example shows how to create customized exceptions by
extending java.lang.Throwable class.
class MyException extends Throwable
{
//Customized Exception class
}
class ThrowAndThrowsExample
{
void method() throws MyException
{
MyException e = new MyException();
throw e;
}
}
NOTE:-
• The java.lang.Throwable.initCause() method initializes the cause of this throwable to the specified
value. (The cause is the throwable that caused this throwable to get thrown.)
• It is generally called from within the constructor, or immediately after creating the throwable
 DECLARATION
 Following is the declaration for java.lang.Throwable.initCause() method
• public Throwable initCause(Throwable cause)

6
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

 Parameters
• cause -- This is the cause (which is saved for later retrieval by thegetCause() method). (A null value is
permitted, and indicates that the cause is nonexistent or unknown.)
• Return Value
This method returns a reference to this Throwable instance.
 Exception
• IllegalArgumentException -- if cause is this throwable.
• IllegalStateException -- if this throwable was created with Throwable(Throwable) or
Throwable(String,Throwable), or this method has already been called on this throwable.
 EXAMPLE
• The following example shows the usage of java.lang.Throwable.initCause() method.
import java.lang.*;
public class ThrowableDemo
{
public static void main(String[] args) throws Throwable
{
try OUTPUT:-
{ Exception in thread "main" amitException: This is my
Exception1(); Exception....
at ThrowableDemo.Exception1(ThrowableDemo.java:18)
} at ThrowableDemo.main(ThrowableDemo.java:6)
catch(Exception e) Caused by: otherException: This is any other Exception....
{ at ThrowableDemo.Exception2(ThrowableDemo.java:27)
System.out.println(e); at ThrowableDemo.Exception1(ThrowableDemo.java:15)
} ... 1 more
}
public static void Exception1()throws amitException
{
try
{
Exception2();
}
catch(otherException e)
{
amitException a1 = new amitException();
// initializes the cause of this throwable to the specified value.
a1.initCause(e);
throw a1;
}
}
public static void Exception2() throws otherException
{
throw new otherException();
}
}
class amitException extends Throwable
{
amitException()
{
7
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

super("This is my Exception....");
}
}
class otherException extends Throwable
{
otherException()
{
super("This is any other Exception....");
}
}
 HIERARCHY OF EXCEPTIONS IN JAVA.
• java.lang.Throwable :
java.lang.Throwable is the super class of all errors and exceptions in java. Throwable class extends
java.lang.Object class. The only argument of catch block must be it’s type or it’s sub class type. You can
check the documentation of Throwable class here. It has two sub classes.
1)java.lang.Error
2)java.lang.Exception
1) java.lang.Error :
java.lang.Error is the super class for all types of errors in java. You can follow the documentation of Error
class here. Some of the common errors are,
• java.lang.VirtualMachineError : The most common virtualMachineErrors are StackOverFlowError and
OutOfMemoryError.
• java.lang.AssertionError
• java.lang.LinkageError : The common LinkageError are NoClassDefFoundError and subclasses
ofIncompatibleClassChangeError. The most frequent IncompatibleClassChangeErrors are
NoSuchMethodError, NoSuchFieldError, AbstractMethodError, IllegalAccessError and
InstantiationError.
All sub classes of Error class are unchecked type of exceptions. i.e They occur during run time only.
2) java.lang.Exception :
java.lang.Exception is the super class for all types of Exceptions in java. You can follow the documentation of
Exception class here. All sub classes of Exception class except sub classes of RunTimeException are checked
type of exceptions. Some of the common sub classes of Exception are,
• java.lang.RunTimeException
All sub classes of RunTimeException are unchecked type of exceptions. i.e They occur during run time only.
Some common RunTimeException are ArithmeticException, NumberFormatException, NullPointerException,
ArrayIndexOutOfBoundsException and ClassCastException.
• All below classes are placed in java.lang package.
 java.lang.InterruptedException
 java.lang.IOException
 java.lang.SQLException
 java.lang.ParseException
 java.langClass Throwable java.lang.Object and java.lang.Throwable
• All Implemented Interfaces:
 Serializable
• Direct Known Subclasses:
 Error, Exception

8
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

 SYNTAX:-
public class Throwable
• extends Object
• implements Serializable
 EXPLANATION:-
 The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects
that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can
be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the
argument type in a catch clause. For the purposes of compile-time checking of
exceptions, Throwable and any subclass of Throwable that is not also a subclass of
either RuntimeException or Error are regarded as checked exceptions.
 Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional
situations have occurred. Typically, these instances are freshly created in the context of the
exceptional situation so as to include relevant information (such as stack trace data).
 A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can
also contain a message string that gives more information about the error. Over time, a throwable
can suppress other throwables from being propagated. Finally, the throwable can also contain a cause:
another throwable that caused this throwable to be constructed. The recording of this causal
information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so
on, leading to a "chain" of exceptions, each caused by another.
 One reason that a throwable may have a cause is that the class that throws it is built atop a lower
layered abstraction, and an operation on the upper layer fails due to a failure in the lower layer. It
would be bad design to let the throwable thrown by the lower layer propagate outward, as it is
generally unrelated to the abstraction provided by the upper layer. Further, doing so would tie the API
of the upper layer to the details of its implementation, assuming the lower layer's exception was a
checked exception. Throwing a "wrapped exception" (i.e., an exception containing a cause) allows the
upper layer to communicate the details of the failure to its caller without incurring either of these
shortcomings. It preserves the flexibility to change the implementation of the upper layer without
changing its API (in particular, the set of exceptions thrown by its methods).
 A second reason that a throwable may have a cause is that the method that throws it must conform to
a general-purpose interface that does not permit the method to throw the cause directly. For example,
suppose a persistent collection conforms to the Collection interface, and that its persistence is
implemented atop java.io. Suppose the internals of the add method can throw an IOException. The
implementation can communicate the details of the IOException to its caller while conforming to
the Collection interface by wrapping the IOException in an appropriate unchecked exception. (The
specification for the persistent collection should indicate that it is capable of throwing such
exceptions.)
 DIFFERENCE BETWEEN THROW VS THROWS IN JAVA
throw vs throws in Java
throw and throws are two Java keyword related to Exception feature of Java programming language. If you are
writing Java program and familiar with What is Exception in Java, its good chance that you are aware of What
is throw and throws in Java. In this Java tutorial we will compare throw vs throws and see some worth noting
difference between throw and throws in Java. Exception handling is an important part of Java
programming language which enables you to write robust programs. There are five keywords related to
Exception handling in Java e.g. try, catch, finally, throw and throws.
1) throw keyword is used to throw Exception from any method or static block in Java while throws keyword,
used in method declaration, denoted which Exception can possible be thrown by this method.
9
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

2) If any method throws checked Exception as shown in below Example, than caller can either handle this
exception by catching it or can re throw it by declaring another throws clause in method declaration.
public void read() throws IOException
{
throw new IOException();
}
failure to either catch or declaring throws in method signature will result in compile time error.
3) throw keyword can be used in switch case in Java but throws keyword can not be used anywhere except on
method declaration line.
4) As per Rules of overriding in Java, overriding method can not throw Checked Exception higher in hierarchy
than overridden method . This is rules for throws clause while overriding method in Java.
5) throw transfers control to caller, while throws is suggest for information and compiler checking.
6) Both Checked and Unchecked Exception can be declared to be thrown using throws clause in Java.

throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with
using throw only. throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.

10
JAVA PART=19 CHIRADIP BASU=9874488038/9903616736

HIERARCHY OF EXCEPTIONS IN JAVA THROUGH “THROWABLE” KEYWORD

11

You might also like