0% found this document useful (0 votes)
7 views18 pages

Try Catch

The document discusses exception handling in Java, specifically focusing on division by zero and how it affects program flow. It explains the use of try-catch blocks to manage exceptions, the types of exceptions, and provides code examples illustrating these concepts. Additionally, it emphasizes the importance of exceptions in preventing program crashes and maintaining code reliability.

Uploaded by

regatonmagdalino
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

Try Catch

The document discusses exception handling in Java, specifically focusing on division by zero and how it affects program flow. It explains the use of try-catch blocks to manage exceptions, the types of exceptions, and provides code examples illustrating these concepts. Additionally, it emphasizes the importance of exceptions in preventing program crashes and maintaining code reliability.

Uploaded by

regatonmagdalino
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ISMAEL MATHAY SR.

HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City
1
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

“Imagine you're building


a calculator app”.
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

What happens if the


user tries to divide by
zero?
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

•For integers (int, long):


• Division by zero causes a runtime error.
• Specifically, Java throws an ArithmeticException.
• Example:
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

• For floating-point numbers (, ):


• Division by zero does not throw an exception.
• Instead, Java follows IEEE 754 floating-point rules:
• Positive number ÷ 0 →
• Negative number ÷ 0 →
• 0 ÷ 0 → (Not a Number)
import [Link]; case '-':
public class SimpleCalculator { result = num1 - num2;
public static void main(String[] args) { [Link]("Result: " + result);
Scanner scanner = new Scanner([Link]); break;
case '*':
// Ask user for two numbers [Link]("Enter result = num1 * num2;
first number: "); [Link]("Result: " + result);
double num1 = [Link](); break;
[Link]("Enter second number: "); case '/':
double num2 = [Link](); if (num2 != 0) {
result = num1 / num2;
// Ask user for operation [Link]("Choose [Link]("Result: " + result);
an operation (+, -, *, /): "); } else {
char operator = [Link]().charAt(0); [Link]("Error: Division by zero is not
allowed.");
double result; }
// Perform calculation based on operator break;
switch (operator) { default:
case '+': [Link]("Invalid operator!");
result = num1 + num2; break;
[Link]("Result: " + result); }
break; [Link]();
}}
import [Link]; case '-':
public class SimpleCalculator { result = num1 - num2;
public static void main(String[] args) { [Link]("Result: " + result);
Scanner scanner = new Scanner([Link]); break;
case '*':
// Ask user for two numbers [Link]("Enter result = num1 * num2;
first number: "); [Link]("Result: " + result);
double num1 = [Link](); break;
[Link]("Enter second number: "); case '/’:
double num2 = [Link](); result = num1 / num2;
[Link]("Result: " + result);
// Ask user for operation [Link]("Choose break; default:
an operation (+, -, *, /): "); [Link]("Invalid operator!");
char operator = [Link]().charAt(0); break;
}
double result; [Link]();
// Perform calculation based on operator }}
switch (operator) {
case '+':
result = num1 + num2;
[Link]("Result: " + result);
break;
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

How Exceptions Alter Normal


Program Flow
“Using Try-Catch Blocks”
Learning Objectives
By the end of this lesson, students will be able to:
o Explain what exceptions are and how they disrupt normal
program flow.
o Identify common types of exceptions in Java.
o Use try-catch blocks to handle exceptions and maintain
program stability.
o Predict and trace program output with and without exception
handling.
Key Improvements:
•Outer try-catch: Catches invalid inputs (like
entering text instead of numbers).
•Inner try-catch for division: Handles division by
zero safely.
•finally block: Ensures the scanner is closed and
prints a closing message.
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

Key Points About Exceptions in Java


•Definition:
An exception is an object that represents an
error or unexpected event in a program.

•Thrown at runtime:
Unlike compile-time errors, exceptions occur
while the program is running.
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

Types of exceptions:
- Checked exceptions:
Must be handled using try-catch or declared with throws.
Examples: IOException, SQLException.
- Unchecked exceptions:
Occur due to programming mistakes and don’t need
explicit handling. Examples: ArithmeticException,
NullPointerException.
- Errors:
Serious problems that applications usually cannot recover
from (e.g., OutOfMemoryError).
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

Handling mechanism
- try block
→ contains code that may cause an exception.
- catch block
→ handles the exception if it occurs.
- finally block
→ always executes, often used to close resources.
- throw keyword
→ used to explicitly throw an exception.
- throws keyword
→ used in method signatures to declare exceptions.
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

public class ExceptionExample {


public static void main(String[] args) {
try {
int num = 10 / 0; // Division by zero
[Link]("Result: " + num);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed!");
} finally {
[Link]("Program finished.");
}
}
}
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

Why Exceptions Matter


➢ They prevent program crashes by catching errors
gracefully.
➢ They make code more robust and reliable.
➢ They allow developers to separate error-handling
logic from normal program logic.
ISMAEL MATHAY SR. HIGH SCHOOL
Branches Ext., GSIS Village, Barangay Sangandaan , Quezon City

In short: Exceptions are Java’s way of signaling


and handling runtime problems so your program
can continue running safely.
Would you like me to also create a visual diagram
showing the flow of try → catch → finally for
your students? That could make the concept more
intuitive.
Java Try-Catch Sample: Handling FileNotFoundException
import [Link];
import [Link];
import [Link];

public class FileReadExample {


public static void main(String[] args) {
try {
File file = new File("[Link]");
Scanner reader = new Scanner(file);
while ([Link]()) {
String line = [Link]();
[Link](line);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("Error: File not found.");
}
[Link]("Program continues after the catch block.");
}}
Java Try-Catch Sample: Handling Array Index Errors
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};

try {
[Link]("Accessing index 5: " + numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Index is out of bounds.");
}
[Link]("Program continues after the catch
block.");
}
}

You might also like