Section 2
public class TryCatchExample {
public static void main(String[] args) {
try {
int numbers = 9;
int result = number/0;
// This will throw ArrayIndexOutOfBoundsException
} catch (Exception e) {
[Link]("Error: Tried to access an invalid array index.");
[Link]("Exception message: " + [Link]());
}
finally{
}
[Link]("Program continues after try-catch block.");
}
}
public class ThrowExample {
public static void main(String[] args) {
int n1 = 15;
int divider =0;
if (divider == 0) {
// Manually throwing an exception
throw new ArithmeticException("You must be 18 or older.");
}else{
[Link]("You are allowed to vote.");
}
}
import [Link];
public class ThrowsExample {
// This method declares it might throw an IOException
static void checkFile() throws IOException {
// Simulating an error
throw new IOException("File not found!");
}
public static void main(String[] args) {
try {
checkFile(); // This must be handled with try-catch
} catch (IOException e) {
[Link]("Caught exception: " + [Link]());
}
[Link]("Program continues...");
}
}
public class MethodExample {
// Defining a method
public static void greet(String name) {
[Link]("Hello, " + name + "!");
}
public static void main(String[] args) {
// Calling the method
greet("Alice");
greet("Bob");
PrintInformation(3,1.7f,"yassin");
}
}
void PrintInformation(int age ,float height, String name ){
//
[Link](name +'age'+age+''+height )
}
/ recursion example
public class RecursionExample {
// Recursive method to calculate factorial
public static int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int number = 5;
int result = factorial(number);
[Link]("Factorial of " + number + " is: " + result);
}
}