public class ThrowExample {
// Method to divide two numbers
static int divide(int a, int b) {
if (b == 0) {
// Explicitly throwing an exception
throw new ArithmeticException(“Cannot divide by zero!”);
}
return a / b;
}
public static void main(String[] args) {
try {
int result = divide(10, 0); // Will trigger the exception
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception caught: ” + e.getMessage());
}
System.out.println(“Program continues…”);
}
}
public class DivideByZeroThrows {
// Method declaring exception using throws
static int divide(int a, int b) throws ArithmeticException {
return a / b; // May throw ArithmeticException
}
public static void main(String[] args) {
try {
int result = divide(10, 0); // Calling method
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception handled: Cannot divide by zero.”);
}
System.out.println(“Program continues…”);
}
}
import java.io.FileReader;
import java.io.IOException;
public class ReadNumbers {
public static void main(String[] args) {
try {
FileReader fr = new FileReader(“numbers.txt”);
int ch;
while((ch = fr.read()) != –1){
System.out.print((char)ch);
}
fr.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
import java.io.FileReader;java.io package.import java.io.IOException;ReadNumbers.This is the starting point of the Java program.
Explanation:
| Keyword | Meaning |
|---|---|
public | accessible from anywhere |
static | can run without creating object |
void | does not return value |
main() | program execution starts here |
try.Explanation:
FileReader → class used to read characters from filefr → object of FileReader"numbers.txt" → file to be readSo this line means:
Open the file numbers.txt for reading
If the file does not exist, an IOException occurs.
ch stores the character read from the fileread() returns an integer value (ASCII/Unicode)Example:
| Character | ASCII Value |
|---|---|
| 1 | 49 |
| 2 | 50 |
| space | 32 |
This is the most important line.
fr.read() reads one character from the fileread() returns –1Example file content:
Characters read:
| Step | Character | ASCII |
|---|---|---|
| 1 | 1 | 49 |
| 2 | 0 | 48 |
| 3 | space | 32 |
| 4 | 2 | 50 |
| 5 | 0 | 48 |
ch contains ASCII value(char)ch converts it to actual characterExample:
Value in ch | After (char) | Output |
|---|---|---|
| 49 | ‘1′ | 1 |
| 48 | ‘0′ | 0 |
So the program prints the same content as the file.
Handles errors during file reading.
Example errors:
If an error occurs, it prints the exception message.