I'm trying to understand some code written by someone else, and do not understand how 'throws' is used there. Here's the code:
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class WhoisQuery {
public static void main(String[] args) throws Exception {
String domainNameToCheck = "abcnews.com";
performWhoisQuery("whois.enom.com", 43, domainNameToCheck);
performWhoisQuery("whois.internic.net", 43, domainNameToCheck);
}
public static void performWhoisQuery(String host, int port, String query) throws Exception {
System.out.println("**** Performing whois query for '" + query + "' at " + host + ":" + port);
Socket socket = new Socket(host, port);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(query);
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
As I understand, code with throws should be handled in some way. However, there's no handling mechanism like try catch. So what's the exact purpose of throws here? I tested it, and without throws it returned IOexception.
My questions are:
- Is throws part written correctly? I assume some handling mechanism should be here, but I am not confident.
- Why does the code work now, and does not without 'throws' in this state? Should it not return an error without catch/try statements? I do not see a difference between no 'throws' and throws without catch/try.