Use of try and catch in Java

By: Manoj Kumar  

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
error
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);
}
}
}




Archived Comments

1. Atetageu
View Tutorial          By: Ayurusat at 2017-09-05 11:08:10

2. Asawoniw
View Tutorial          By: Atakugab at 2017-09-01 13:09:26

3. Hii,
Very Informative, Thanks for sharing.

View Tutorial          By: priya at 2017-08-31 09:35:53

4. Akawozoras
View Tutorial          By: Arikimemar at 2017-07-04 11:25:08

5. Ashigofudon
View Tutorial          By: Amobunofuq at 2017-06-28 04:28:55

6. Akuerenac
View Tutorial          By: Agikedzutom at 2017-06-08 03:02:11

7. Accurate explanation
thanks a lot

View Tutorial          By: Raunit at 2017-05-25 14:07:00

8. jimmieng4
View Tutorial          By: marcij4 at 2017-05-20 02:40:01

9. Azasazoq
View Tutorial          By: Aboarob at 2017-05-16 02:36:38

10. sashaik60
View Tutorial          By: ianqe3 at 2017-04-22 17:57:05

11. nicholaswh11
View Tutorial          By: lisaxs18 at 2017-03-30 05:01:31

12. beulahvi2
View Tutorial          By: marianneyz60 at 2017-01-18 08:17:27

13. Very helpful!!
View Tutorial          By: Ankit at 2016-12-09 08:41:59

14. sir
if v hv a long and complex code is there any method to handle a static or sequential exc

View Tutorial          By: sayali pujari at 2016-01-05 06:21:20

15. Bhau... lay Bhari ..Lay bhari
Akach Number!

View Tutorial          By: Abdul Vinod Farnadizz at 2015-06-20 06:15:40

16. 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

17. Useful info
View Tutorial          By: valli at 2014-10-27 10:56:58

18. thnx
View Tutorial          By: code master at 2014-07-30 13:56:24

19. Thank so much it helped me God bless :)
View Tutorial          By: Judito at 2014-06-14 06:52:18

20. Thank so much it helped me God bless :)
View Tutorial          By: Judito at 2014-06-14 06:49:05

21. super
View Tutorial          By: asasdfsa at 2014-05-29 05:23:04

22. i dont understand
View Tutorial          By: amabelle pascual at 2014-01-09 23:47:14

23. Very simple and easy to understand... Thank u...
View Tutorial          By: Anu Priya at 2013-07-22 09:00:19

24. Very simple and easy to understand... Thank u...
View Tutorial          By: Anu Priya at 2013-07-22 08:59:19

25. Easy to understand........ thanks man
View Tutorial          By: vikash bhardwaj at 2013-06-25 07:07:54

26. i understand but i want many information and programs
View Tutorial          By: malathi at 2013-03-29 23:52:28

27. good explanation
View Tutorial          By: Vishu Sharma at 2013-03-13 13:57:11

28. too good post....very easy to understand
View Tutorial          By: Rahul at 2013-03-04 17:09:58

29. well explained.. Thanq :)
View Tutorial          By: Aparna at 2013-03-01 06:08:35

30. you made it so easy thank you!!
View Tutorial          By: naveen at 2013-02-23 12:58:48

31. 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

32. good information
View Tutorial          By: varun at 2013-01-04 14:51:19

33. It's very clear explanation. thank you
View Tutorial          By: miroot at 2012-12-27 17:46:14

34. Barely can understand it even I'm a NEWBIES ^^
ThankS

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

35. 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

36. Why do we use the letter e?
View Tutorial          By: Anonymous at 2012-11-14 14:18:02

37. great explaination !!!
View Tutorial          By: aman at 2012-10-02 06:55:55

38. very easy to understand ... a quite a good example ... thank u .. :)
View Tutorial          By: Dinesh at 2012-09-22 18:19:45

39. Oooooooooooooops its tooo hard to understand
View Tutorial          By: ashik at 2012-09-17 15:39:24

40. right to point.. thanks man
View Tutorial          By: manish at 2012-07-28 15:01:26

41. barbara. spelling mistake.. says spank you.. this is bad.. correct yourself
View Tutorial          By: abcd at 2012-04-24 08:48:23

42. thanks ! really helpful !
View Tutorial          By: feliks at 2012-04-11 18:33:52

43. it provides manna in the studies of java to me
View Tutorial          By: aravinden at 2011-12-27 08:18:18

44. WHATEVER :)
View Tutorial          By: Ian at 2011-10-18 07:57:52

45. thanks!
View Tutorial          By: me den at 2011-02-26 18:37:42

46. great
View Tutorial          By: ellaine at 2010-10-18 06:31:14

47. Simple and straight to the point. Thank you.
View Tutorial          By: Barbara at 2008-03-21 10:02:47


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial