File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Catching Ctrl C Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Catching Ctrl C" Watch "Catching Ctrl C" New topic

Catching Ctrl C

Chinmay Bajikar
Ranch Hand

Joined: Dec 08, 2001
Posts: 159
Hi all,
I have a Java GUI Application which has a Db connection.
Now when the application window is closed using the normal 'X' button on the top right corner,I can catch the WindowClosing event and close the db connection.
But since the application is running from a dos prompt,I can even close it using a Ctrl C.
Is there any way for me to catch the Ctrl C and the take appropriate action like closing the open db connections?
Thanks in advance,

The strength of the Wolf is the pack & the strength of the pack is the wolf....Rudyard Kipling
Greg Charles

Joined: Oct 01, 2001
Posts: 2963

Runtime.addShutdownHook(Thread hook)
This won't keep the program from terminating, but lets you do some cleanup while it does.
Nilesh Pereira
Ranch Hand

Joined: Apr 14, 2003
Posts: 53
And what happens if someone pulls the plug on the client computer. How do you clean up then?
Rodney Woodruff
Ranch Hand

Joined: Dec 04, 2001
Posts: 80
You don't clean up. But you could put some start up code that would try to fix what was not properly released during the last running of the application. This could be rebuilding logs or reporting on last state of the application.
However, outside of using a UPS, there is no such thing as a "Loss of Power Exception or Event"

Hope This Helps
Nilesh Pereira
Ranch Hand

Joined: Apr 14, 2003
Posts: 53
My point exactly. Which is why I don't think it's a good practice to trap Ctrl-C. What if the user does an "end task" in Windows, or "kill -9" in UNIX... or the network dies... or a hard disk crashes. There are just too many possibilities. It makes better sense to do damage control either on the server side, or while starting up as Rodney ponted out.
Chinmay Bajikar
Ranch Hand

Joined: Dec 08, 2001
Posts: 159
Point accepted Nilesh!
But when u r working on a single db connection,u have to try and plug as many ambuities as u can.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Catching Ctrl C
It's not a secret anymore!