Code Comments
Programming Forum and web based access to our favorite programming groups.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
Post Follow-up to this messagetry 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.
Post Follow-up to this messageIn 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
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.