הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Exceptions Examples

The example relates to Willie's Chocolate factory and the machines at work in the factory. In Willie's factory, there are 10 chocolate making factories, each machine produces chocolates until it gets broken. Like in real life, some problems are worth fixing while others are not. Willie looks after his machines, and if there's something worth fixing he fixes it and gets it up and running again, otherwise the machine is thrown away.
Note the BrokenMachineException:

  1. It extends Exception so we can throw it
  2. It holds some extra data (the machine's age) and an extra method. They are the reason we created this class
  3. It creates its own error message that is more explanatory than the standard
public class BrokenMachineException extends Exception {
	private int age;
 
	public BrokenMachineException(int age) {
		super("This machine is broken and its age is " + age);
		this.age = age;
	}
 
	public boolean isItWorthFixing() {
		return age < 10;
	}
}
public class ChocoMachine {
	private int age;
	private int numProducts;
	private boolean broken;
 
	public ChocoMachine() {
		this.age = (int) (Math.random() * 34);
		this.numProducts = 0;
		this.broken = false;
	}
 
	public void fix() {
		this.broken = false;
	}
 
	public void produce(int amt) throws BrokenMachineException {
		if ( this.broken ) {
			throw new BrokenMachineException(this.age);
		}
 
		for (int i=0; i < amt; i++ ) {
			System.out.println("Yummy");			
			this.numProducts += 1;
 
			if (  this.numProducts % 7 == 0 ) { 
				this.broken = true;
				throw new BrokenMachineException(this.age);
			}
		}
	}
}
import java.util.HashSet;
import java.util.Set;
 
 
public class WilliesFactory {
	Set<ChocoMachine> machines;
 
	public WilliesFactory() {
		machines = new HashSet<ChocoMachine>();
 
		for ( int i=0; i < 10; i++ ) {
			machines.add(new ChocoMachine());
		}
	}
 
	public void startTheDay() {
		for ( ChocoMachine m : machines ) {
			int amt = (int) (Math.random() * 17);
 
			try {
				m.produce(amt);	
			} 
			catch ( BrokenMachineException e ) {
				System.out.println(" ===> " + e.getMessage() );
				System.out.println("Repair team - get to work !");
				if ( e.isItWorthFixing() ) {
					m.fix();	
				} else {
					System.out.println("To the junk yard");
				}
			}
 
		}
	}
}
import java.util.HashSet;
import java.util.Set;
 
 
public class Main {
	public static void main(String [] args) {
		WilliesFactory f = new WilliesFactory();
		f.startTheDay();
	}
}
course: