Use of 'throw' in Java

By: Priya Emailed: 1647 times Printed: 2112 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:

throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.

The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.

// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown.

Here is the resulting output:

Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

The program also illustrates how to create one of Java's standard exception objects. Pay close attention to this line:

throw new NullPointerException("demo");

Here, new is used to construct an instance of NullPointerException. All of Java's built-in run-time exceptions have two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

like

View Tutorial          By: po!X!on at 2011-05-05 01:30:51

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Priya
Getting started with ASP
EJB Entity Beans
Error Handling - Stderr and Exit - sample program in C
Pointers and Arrays in C
Data Types and Sizes in C
virtual inheritance example in C++
ctime() sample program in C++
TextBox sample program in J2ME
Advantages of Java Beans
list() contents of a Directory - sample program in Java
File example program in Java
continue and break statements in C++
Use of 'throw' in Java
Passing parameters to a function by value in C++
Demonstrating global and local variables in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Read from a COM port using Java program
FileReader and FileWriter example program in Java
append() in Java
Student marks calculation program in Java
Recursion in java
Vector example in Java
XML and Java - Parsing XML using Java Tutorial
Increment and Decrement Operator
Stack example in Java - push(), pop(), empty(), search()
wait(), notify() and notifyAll() in Java - A tutorial
Using StringTokenizer in Java
Sample Java program shows how to write to COM port using Java.
Count number of vowels, consonants and digits in a String in Java
Execute system commands in a Java Program
Most Emailed Articles (in Java)
What is Multithreaded programming?
TCP Server and TCP Client in Java
for loop in java
Read from a COM port using Java program
Calculate gross salary in Java
Calculate average sale of the week in Java
wait(), notify() and notifyAll() in Java - A tutorial
setPriority() and getPriority() in Java
Window Object
constants and variables
Type Casting in Java
Basics of Exception Handling in Java
? - ternary (three-way) operator - in Java
Why java is important to the Internet
Update contents of a file within a jar file