Handling Exceptions in Web Server Example
This program demonstrates handling exceptions in web servers.
Problem Statement
Write a Java program that handles exceptions in a simple HTTP server.
Source Code
| 1 | import com.sun.net.httpserver.*; |
| 2 | import java.io.*; |
| 3 | public class WebServerExceptionExample { |
| 4 | public static void main(String[] args) throws IOException { |
| 5 | System.out.println("Eduinq Web Server Exception Example"); |
| 6 | HttpServer server=HttpServer.create(new java.net.InetSocketAddress(8000),0); |
| 7 | server.createContext("/test",exchange -> { |
| 8 | try { |
| 9 | int result=10/0; |
| 10 | String response="Eduinq Result: "+result; |
| 11 | exchange.sendResponseHeaders(200,response.length()); |
| 12 | OutputStream os=exchange.getResponseBody(); |
| 13 | os.write(response.getBytes()); |
| 14 | os.close(); |
| 15 | } catch(Exception e) { |
| 16 | String response="Eduinq Exception: "+e.getMessage(); |
| 17 | exchange.sendResponseHeaders(500,response.length()); |
| 18 | OutputStream os=exchange.getResponseBody(); |
| 19 | os.write(response.getBytes()); |
| 20 | os.close(); |
| 21 | } |
| 22 | }); |
| 23 | server.start(); |
| 24 | } |
| 25 | } |
Program Output
Eduinq Web Server Exception Example Eduinq Exception: / by zero
Explanation
Web servers must handle exceptions to prevent crashes. - Try-catch ensures meaningful error responses to clients. - Improves reliability and user experience. - In enterprise systems, web server exception handling ensures stable services. Conclusion: Shows handling exceptions in web servers.