Commit 6be803f2 authored by Bhargavi Ghanta's avatar Bhargavi Ghanta

Initial commit

parent 062f2b34
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class GlobalExceptionHandler {
public static void main(String[] args) {
// Set global exception handler
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
// Simulate an unhandled exception
System.out.println("Program started...");
String value = null;
System.out.println(value.length()); // This will throw NullPointerException
}
// Custom global exception handler
static class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
try (PrintWriter writer = new PrintWriter(new FileWriter("error_log.txt", true))) {
writer.println("=== Uncaught Exception in thread \"" + t.getName() + "\" ===");
writer.println("Exception: " + e);
for (StackTraceElement element : e.getStackTrace()) {
writer.println("\tat " + element);
}
writer.println(); // blank line between exceptions
} catch (IOException ioException) {
System.err.println("Failed to write to log file: " + ioException.getMessage());
}
}
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class GlobalExceptionLogger {
public static void main(String[] args) {
// Set up global exception handler
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
logException(throwable);
});
// Sample code that throws an unhandled exception
System.out.println("Program started.");
int result = divide(10, 0); // This will cause ArithmeticException
System.out.println("Result: " + result);
}
// Method that may throw an exception
public static int divide(int a, int b) {
return a / b; // division by zero triggers an exception
}
// Method to log exceptions to a file
public static void logException(Throwable throwable) {
try (PrintWriter writer = new PrintWriter(new FileWriter("error.log", true))) {
writer.println("----- Exception Occurred -----");
writer.println("Thread: " + Thread.currentThread().getName());
writer.println("Exception: " + throwable);
for (StackTraceElement element : throwable.getStackTrace()) {
writer.println("\tat " + element);
}
writer.println(); // Blank line for separation
} catch (IOException e) {
System.err.println("Failed to log exception: " + e.getMessage());
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment