Unit 3: Exception handling and applet/graphics programming
Programming in Java notes · PTU syllabus (BSIT502/BSBC502)
On this page
- Unit summary
- Types of errors and exceptions
- try, catch and finally
- Throwing custom exceptions
- Applets and the applet life cycle
- Creating an executable applet and passing parameters
- The Graphics class: lines, rectangles, circles, ellipses, arcs and polygons
- Line graphs and bar charts
- Key terms
- Quick revision
- Important questions
Unit summary
Robust programs handle errors gracefully, and Java can draw graphics. This unit covers types of errors and exceptions, try, catch and finally blocks, throwing custom exceptions, the applet life cycle, creating and running applets, passing parameters, the Graphics class, drawing lines, rectangles, circles, ellipses, arcs and polygons, and drawing line graphs and bar charts.
After this unit you can
- Handle exceptions with try, catch and finally
- Throw and create custom exceptions
- Explain the applet life cycle and pass parameters
- Draw shapes and charts using the Graphics class
PTU syllabus topics
- Types of errors and exceptions
- try/catch/finally blocks
- throwing custom exceptions
- applet life cycle
- creating executable applets
- passing parameters
- the Graphics class
- drawing lines/rectangles/circles/ellipses/arcs/polygons
- line graphs and bar charts
- 1. init(): Called once to set up
- 2. start(): Applet becomes active
- 3. paint(): Draws on screen
- 4. stop(): Applet leaves view
- 5. destroy(): Final clean-up
Topic 1
Types of errors and exceptions
Detected by
javac
JVM while running
Examples
Missing semicolon, undeclared variable, type mismatch
Division by zero, array index out of bounds, null reference
Result
No .class file produced
Exception thrown; program stops if unhandled
Error
Serious problems — OutOfMemoryError, StackOverflowError; not handled
Checked exceptions
Checked at compile time — IOException, SQLException, FileNotFoundException
Unchecked (RuntimeException)
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException
Topic 2
try, catch and finally
javatry {
int[] a = new int[3];
int x = Integer.parseInt("12a"); // NumberFormatException
a[5] = 10 / 0;
} catch (ArithmeticException | NumberFormatException e) { // multi-catch
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Other error");
} finally {
System.out.println("Always runs — close files here");
}
try (java.io.FileReader fr = new java.io.FileReader("a.txt")) { // try-with-resources
System.out.println((char) fr.read());
} catch (java.io.IOException e) { e.printStackTrace(); }Topic 3
Throwing custom exceptions
javaclass InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) { super(msg); }
}
class Account {
double balance = 5000;
void withdraw(double amt) throws InsufficientBalanceException { // declares it
if (amt > balance) throw new InsufficientBalanceException("Balance too low");
balance -= amt;
}
}
// caller
try { new Account().withdraw(8000); }
catch (InsufficientBalanceException e) { System.out.println(e.getMessage()); }- throw raises an exception object; throws declares exceptions a method may pass on.
Topic 4
Applets and the applet life cycle
- Applet: a small Java program embedded in a web page and run by a browser plug-in or appletviewer. Applets are now obsolete — browsers removed plug-in support, appletviewer was dropped in JDK 11 and the Applet API is deprecated — but the concepts carry over to GUI programming and remain in the syllabus.
- 1. init(): Called once to initialise
- 2. start(): Called after init and whenever the page is revisited
- 3. paint(Graphics g): Draws output; called on repaint
- 4. stop(): Called when the page is left
- 5. destroy(): Called once before the applet is removed
Entry point
init(), no main()
main()
Runs in
Browser or appletviewer
JVM directly
Security
Sandboxed — no local file access
Full access
Status
Obsolete
Standard
Topic 5
Creating an executable applet and passing parameters
javaimport java.applet.Applet;
import java.awt.*;
public class Welcome extends Applet {
String name;
public void init() {
name = getParameter("student"); // read PARAM
if (name == null) name = "Guest";
setBackground(Color.yellow);
}
public void paint(Graphics g) { g.drawString("Welcome, " + name, 40, 50); }
}html<!-- Welcome.html -->
<applet code="Welcome.class" width="300" height="120">
<param name="student" value="Simran">
</applet>- Run with appletviewer Welcome.html (JDK 8 or earlier). The same drawing code can run today inside a JFrame or JPanel by overriding paint or paintComponent.
Topic 6
The Graphics class: lines, rectangles, circles, ellipses, arcs and polygons
javapublic void paint(Graphics g) {
g.setColor(Color.blue);
g.drawLine(10, 10, 150, 10); // x1, y1, x2, y2
g.drawRect(10, 30, 100, 50); // x, y, width, height
g.fillRoundRect(130, 30, 100, 50, 20, 20);
g.drawOval(10, 100, 80, 80); // circle: equal width and height
g.drawOval(110, 100, 120, 60); // ellipse
g.drawArc(250, 100, 80, 80, 0, 180); // start angle 0, sweep 180
int[] xs = {300, 350, 400}, ys = {250, 180, 250};
g.fillPolygon(xs, ys, 3); // triangle
g.setFont(new Font("Arial", Font.BOLD, 16));
g.drawString("Shapes", 10, 220);
}Topic 7
Line graphs and bar charts
javapublic void paint(Graphics g) {
int[] sales = {40, 75, 60, 90, 55};
String[] yr = {"2021", "2022", "2023", "2024", "2025"};
g.drawLine(40, 250, 360, 250); // x-axis
g.drawLine(40, 250, 40, 40); // y-axis
for (int i = 0; i < sales.length; i++) {
int x = 60 + i * 60, h = sales[i] * 2;
g.setColor(Color.orange);
g.fillRect(x, 250 - h, 30, h); // bar
g.setColor(Color.black);
g.drawString(yr[i], x, 265);
if (i > 0) { // line graph joining bar tops
int px = 60 + (i - 1) * 60 + 15, ph = sales[i - 1] * 2;
g.drawLine(px, 250 - ph, x + 15, 250 - h);
}
}
}Key terms
- Exception
- Event that disrupts normal program flow
- Checked exception
- Exception the compiler requires to be handled or declared
- finally
- Block that always executes after try
- Applet
- Small Java program embedded in a web page (now obsolete)
- Graphics class
- AWT class providing drawing methods
Quick revision
- Compile-time vs run-time errors; Throwable, Error, Exception; checked vs unchecked.
- try, catch, multi-catch, finally, try-with-resources.
- throw vs throws; custom exception classes.
- init, start, paint, stop, destroy; PARAM and getParameter.
- drawLine, drawRect, drawOval, drawArc, drawPolygon, fill methods; charts.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Distinguish checked and unchecked exceptions.
- Q2.What is the use of finally?
- Q3.Distinguish throw and throws.
- Q4.List the applet life-cycle methods.
- Q5.How are parameters passed to an applet?
- Q6.How do you draw a circle with the Graphics class?
Long-answer questions
- Q1.Explain exception handling in Java with programs.
- Q2.Write a program to create and throw a custom exception.
- Q3.Explain the applet life cycle and parameter passing.
- Q4.Write a program to draw shapes and a bar chart using the Graphics class.
Stuck on this unit?
Message SBS on WhatsApp for help with Programming in Java, or to ask about studying B.Sc IT at Synetic.
