Exceptions in Java
Exceptions are used to handle errors and unexpected situations in your code. You can use try-catch blocks to catch and handle exceptions that might occur during runtime.
Example code:
csharp
try {
int result = divide(10, 0);
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return a / b;
}
No comments:
Post a Comment