Exceptions are available in many different languages and are used in many different ways. Java follows C++'s exception handling closely, but leaves many (unnecessary) parts out.
You can also define your own exceptions instead of the ones pre-defined by extending the Exception class and providing some extra functionality.void MethodThatDies() throws NullPointerException, KitchenSinkException
try/finally catches all exceptions.int value; try { for(x=0, value = 100;x < 100; x++) { value = value / x; } } catch(ArithmeticException e) { System.out.println("Foolish mathematics") } catch(Exception e) { System.out.println("An error has occurred - scream for your life"); }
There is no reason why in your catch block why you would not rethrow the exception if you didn't want to handle it.public class ErrorDialog extends Dialog { ErrorDialog(Frame parent) { super(parent, true); setLayout(new BorderLayout()); // A panel with Contine and Exit buttons Panel p = new Panel(); p.add(new Button("Continue?")); p.add(new Button("Exit")); add("Center", new Label("An error has occurred. Continue?")) add("South", p); } public boolean action(Event evt, Object arg) { if("Exit".equals(arg)) { dispose(); System.exit(1); } return false; } } .. // somewhere in a class try { // Dangerous stuff here } catch(SomeException e) { ErrorWindow = new ErroDialog(this); ErrorWindow.show(); }
Good places for exception handling to be(and sometimes they are required)
Q: What else is so great about exceptions?
A: Remember #ifdef DEBUG ...? Well exceptions can replace such code and error processing can be centralized regardless of platform. i.e under UNIX signal were a form of exceptions, but it's not portable to other OSes.Q: javac keeps on giving me this warning "must be caught or thrown, blah, blah"?
A: A exception might occur there. You must either handle it there or rethrow the exception.Q: What are the most common Exceptions?
A: NullPointerException, MalformedURLException, NumberFormatException, IOException..
Graphically threads look like this:
import java.awt.*; import java.applet.*; public class ThreadedApplet extends Applet implements Runnable { Button b1; int x = 0; Thread one = null; // Two buttons, one with a number the other with "Stop" public void init() { add(b1 = new Button("000000")); add("South", new Button("Stop")); } import java.awt.*; import java.applet.*; public class ThreadedApplet extends Applet implements Runnable { Button b1; int x = 0; boolean suspended = false; Thread one = null; // Two buttons, one with a number the other with "Stop" public void init() { add(b1 = new Button("000000")); } public void start() { // Create a new thread with minimum priority // "this" refers to the current class which is a Runnable if(one == null) { x = 0; one = new Thread(this); one.setPriority(Thread.MIN_PRIORITY); one.start(); } } // Called when the Thread is created public void run() { while(true) { b1.setLabel(new Integer(x++).toString()); try { one.sleep(1000); } catch(InterruptedException e) {} } } public boolean mouseDown(Event evt, int x, int y) { if (suspended) { one.resume(); } else { one.suspend(); } suspended = !suspended; return true; } public void stop() { // kill thread one = null; } }
For example, if you wanted a way to draw two images simultaneously, creating another process is rather a back hack, same goes for a application which wants to handle user input while printing or displaying a complex piece of graphics.
Pre-emptive multi-threading has its problems. One thread can interrupt another at any given time, thus the moniker 'pre-emptive'. What if one thread was writing to a array, while the other interrupted that thread and started to write to the same array?
Languages like C and C++ need to lock() and unlock() data before and after reading/writing to it. Java does away with this, it hides it the locking of data via the 'synchronized' keyword. i.e
synchronized int MyMethod();Another areas that threads have proven to be useful is in GUIs. There will be increased responsiveness when the computer is locked in some lengthy calculation or operation and can not handle any user input, with the use of threads. Thus things can be done in the background or multiple things in the foreground(i.e play sound and animations) without 'slowing' or giving the apperance of sluggish performance.
class MyThreads extends Threads { public void run() { } }
class MyThreadedButton extends Button implements Runnable { public Button() { new Thread(this); } public void run() { /// Gets executed when the Thread is created } }You'll need to create an instance of Thread before threading can occur. Thus if your class implemented the interface runnable you could use methods 1,2,4,5. and pass "this" when a Runnable is required.
Q: Difference between using Interface vs. sub-class of Thread for Threading?
A: With the interface, you do not need to create another class w/ a run() method. Rather have the run() method in the class that implements the Runnable interface. run() is called when the tread begins execution. In the case of a sub-class of Thread. It's run() method is called. In both cases you create almost in the same manner.
Q: Why do you have an infinite loop in run()?
A: We loop infinitely until the thread gets interrupted. If the thread never does, then the thread will hog all of the CPU cyclesQ: Why do you call sleep()?
A: To 'delay'(or put asleep) the thread for a few milliseconds(i.e 1000 = 1 sec).
Q: How many threads can you create?A: As many as the system you are using allows. There isn't a limit, but there have been reported cases where the system or program crashes due to a large number of threads.
Q: Is there more information on threading?
A: Yes. Sun's programmer's guides are a good reference for Java-style threads