For Programmers: Free Programming Magazines  


Home > Archive > Java Help > April 2005 > try catch blocks









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author try catch blocks
Irlan agous

2005-04-21, 4:00 pm

Hello,

Can someone telle me what the try catch blocks are doing, is there a simple
tutorial out there?

I dont see the use of this

Thanks

Irlan


Rivky

2005-04-21, 4:00 pm

try catch blocks are a good way of handling errors. You can't always
assume that what you want to do will run smoothly. So you "Try" it, and
if it doesn't work, instead of having the program mess up, you can
catch/handle the error. Take the following example. I get input from a
user. I ask him for 2 numbers and I'm gonna add them up for him. Yet by
mistake, the user entered a character instead of a number. So I'm gonna
try to turn his input into a number so that I can add it, but it won't
work because it's a charachter. So I'll handle that error.

try{
Integer.parseInt(stringEnteredByUsed);
}
catch(NumberFormatException nfe){
// Here I can handle the error and displkay a message to user, your
entry is not valid
}

This is a simple example and there's a lot more involved. Especially
when multiple exceptions can be thrown and you can handle each one in a
different way. Like if it's a certain error do one thing while if it's
another, do something else.

Important thing to realize is that once the program is running, and an
error happens, your program could be entirely messed up. This is
ESPECIALLY true in command line programs. Because if an error is thrown
but not handles, the program will terminate.

Jeffrey Spoon

2005-04-21, 8:58 pm

In message <6a77b$4267aa50$52ade8f3$14206@news.versatel.nl>, Irlan agous
<irlan345@msn.com> writes
>Hello,
>
>Can someone telle me what the try catch blocks are doing, is there a simple
>tutorial out there?
>
>I dont see the use of this
>
>Thanks
>
>Irlan
>
>


Some classes throw Exceptions (errors). You can either catch them, using
a try/catch block, or you have to throw them. If you throw them then
your program may simply crash and print a stack trace when an exception
occurs.

If you catch them, you can handle the error and do something about it,
other than letting your app crash, such as print an error message or
whatever. The try block covers the line of code that causes the
exception and then the catch block contains the code that will be
executed when that exception occurs in the try block.

<http://java.sun.com/docs/books/tuto...ial/exceptions/>

That's a good tutorial from Sun.


--
Jeffrey Spoon

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com