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
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
Example
Checked or unchecked? Opening a file with new FileReader("data.txt") can throw FileNotFoundException, a checked exception — the program will not compile unless it is caught or declared with throws. Dividing by zero throws ArithmeticException and reading a[5] from a 3-element array throws ArrayIndexOutOfBoundsException — both unchecked (subclasses of RuntimeException), so the compiler does not force handling.
Topic 2
try, catch and finally
An exception is an event that disrupts normal program flow. Java handles it with try (risky code), catch (handler), finally (always runs) and throw/throws.
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(); }Example
Handling an exception: try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Done"); } prints both messages instead of crashing.
Exam tip
Checked exceptions (like IOException) must be handled or declared; unchecked ones (like ArithmeticException) need not be.
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.
Example
Tracing try–catch–finally: try { int[] a = new int[3]; System.out.println("A"); a[5] = 1; System.out.println("B"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("C"); } finally { System.out.println("D"); } System.out.println("E"); prints A, C, D, E — "B" is skipped because control jumps to catch at the error, and finally always runs.
Exam tip
With several catch blocks, put the subclass before the superclass — catch (ArithmeticException e) before catch (Exception e). The reverse order is a compile error, because the specific block could never be reached.
Topic 4
Applets and the applet life cycle
Applets are now obsolete — browsers removed Java plug-in support and Java 9 deprecated the Applet API — but the life cycle is still part of many syllabuses.
- 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
Exam tip
Modern browsers no longer run applets — the browser plug-in and appletviewer were removed from JDK 11, and the Applet API is deprecated — but applets remain in the syllabus. Answer with the life-cycle methods init, start, paint, stop and destroy, and run practical programs with appletviewer from JDK 8.
Entry point
init(), no main()
main()
Runs in
Browser or appletviewer
JVM directly
Security
Sandboxed — no local file access
Full access
Status
Obsolete
Standard
Example
The life cycle: when an applet page opens, init() runs once, then start(); paint() draws the output; leaving the page calls stop(); closing the browser calls destroy().
Exam tip
Learn the order: init → start → paint → stop → destroy.
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.
Example
Passing a parameter: the HTML contains <param name="user" value="Asha">, and the applet reads it with String u = getParameter("user"); and draws Welcome, Asha with g.drawString(...).
Exam tip
getParameter() always returns a String — convert numbers with Integer.parseInt().
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.
