Use of try and catch in Java

By: Manoj Kumar Emailed: 1768 times Printed: 2515 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

Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating. Most users would be confused (to say the least) if your program stopped running and printed a stack trace whenever an error occurred! Fortunately, it is quite easy to prevent this.

To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. To illustrate how easily this can be done, the following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error:

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero
System.out.println("Division by zero.");
System.out.println("After catch statement.");

This program generates the following output:

Division by zero.
After catch statement.

Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not "called," so execution never "returns" to the try block from a catch. Thus, the line "This will not be printed." is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement (except in the case of nested try statements, described shortly). The statements that are protected by try must be surrounded by curly braces. (That is, they must be within a block.) You cannot use try on a single statement.

The goal of most well-constructed catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened. For example, in the next program each iteration of the for loop obtains two random integers. Those two integers are divided by each other, and the result is used to divide the value 12345. The final result is put into a. If either division operation causes a divide-by-zero error, it is caught, the value of a is set to zero, and the program continues.

// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
System.out.println("a: " + a);

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


1. View Comment

Simple and straight to the point. Thank you.

View Tutorial          By: Barbara at 2008-03-21 10:02:47
2. View Comment

it provides manna in the studies of java to me

View Tutorial          By: aravinden at 2011-12-27 08:18:18
3. View Comment

right to point.. thanks man

View Tutorial          By: manish at 2012-07-28 15:01:26
4. View Comment

very easy to understand ... a quite a good example ... thank u .. :)

View Tutorial          By: Dinesh at 2012-09-22 18:19:45
5. View Comment

great explaination !!!

View Tutorial          By: aman at 2012-10-02 06:55:55
6. View Comment

Nice work sir... it was very easy to understand keep the good work up////

View Tutorial          By: AsadUllah at 2012-11-20 19:05:29
7. View Comment

Barely can understand it even I'm a NEWBIES ^^

View Tutorial          By: YieonChee at 2012-11-28 17:56:24
8. View Comment

It's very clear explanation. thank you

View Tutorial          By: miroot at 2012-12-27 17:46:14
9. View Comment

good information

View Tutorial          By: varun at 2013-01-04 14:51:19
10. View Comment

It's very easy to learn try / catch functionality... Good Job keep work on it....

View Tutorial          By: Ponraj at 2013-01-31 04:21:06
11. View Comment

well explained.. Thanq :)

View Tutorial          By: Aparna at 2013-03-01 06:08:35
12. View Comment

too good post....very easy to understand

View Tutorial          By: Rahul at 2013-03-04 17:09:58
13. View Comment

good explanation

View Tutorial          By: Vishu Sharma at 2013-03-13 13:57:11
14. View Comment

i understand but i want many information and programs

View Tutorial          By: malathi at 2013-03-29 23:52:28
15. View Comment

Easy to understand........ thanks man

View Tutorial          By: vikash bhardwaj at 2013-06-25 07:07:54
16. View Comment

Very simple and easy to understand... Thank u...

View Tutorial          By: Anu Priya at 2013-07-22 09:00:19
17. View Comment

i dont understand

View Tutorial          By: amabelle pascual at 2014-01-09 23:47:14
18. View Comment


View Tutorial          By: asasdfsa at 2014-05-29 05:23:04
19. View Comment

Thank so much it helped me God bless :)

View Tutorial          By: Judito at 2014-06-14 06:52:18
20. View Comment

Useful info

View Tutorial          By: valli at 2014-10-27 10:56:58
21. View Comment

Hi can anyone tell me how to use try catch in command line arguments?

View Tutorial          By: Gossip Lanka at 2015-04-26 05:00:44

Your name (required):

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

Your sites URL (optional):

Your comments:

More Tutorials by Manoj Kumar
Importing Keystore example using keytool in Java
for loop example in Java
Result Sets, Cursors and Transactions in SQL
JSP Tags for SQL to connect to a database
Using the qsort() and bsearch() functions with values - example program in C
Using qsort() and bsearch() with strings - example program in C
scanf and sscanf sample program in C
Use of {0} is required and Accessing resource bundles programmatically in Struts
Character Arrays in C
Pointers to functions in C++
atoi(), itoa() in C++
Ticker sample program in J2ME
DateFormat sample program in Java
Random class sample program in Java - nextGaussian(), nextBoolean(), nextBytes(), nextInt(), nextLong(), nextFloat(), nextDouble()
What Is a Reference 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 )
InetAddress Example program in Java
Reading from a file and writing to a file using Java program
wait(), notify() and notifyAll() in Java - A tutorial
Use of try and catch in Java
compareTo( ) in Java
Student marks calculation program in Java
Stack example in Java - push(), pop(), empty(), search()
The java Buzzwords
How to use ArrayList in Java
FilenameFilter - sample program in Java
Count number of vowels, consonants and digits in a String in Java
Calculate gross salary in Java
The Basic Structure of a Simple Java program
Read from a COM port using Java program
Vector in Java - Sample Program
Most Emailed Articles (in Java)
Calculate gross salary in Java
Text to Speech conversion program in Java
Insert an element in Array, Search and Sort Array by using java program
How to initialize an Array and how to copy the array
Using Charts in JasperReports
Requesting a Signed Certificate from a Certification Authority example using keytool in Java
switch in java
Multidimensional or arrays of arrays in Java
Using totalMemory( ) and freeMemory( ) in Java
The Benefits of OOP
The features in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File