1

This is a code for finding IP address of a URL. I have problem with compilation. I have put the whole code for clear understanding of my problem. Hope the image would help you. I would also like to know why url is being highlighted in red. Is it the cause of exception? This is the image of editor showing the error

import javax.swing.*;  
import java.awt.event.*;  
import java.net.*;  
public class IP extends JFrame implements ActionListener
{  
    JLabel l;  
    JTextField tf;  
    JButton b;  
IP(){  
    super("IP Finder Tool");  
    l=new JLabel("Enter URL:");  
    l.setBounds(50,70,150,20);;  
    tf=new JTextField();  
    tf.setBounds(50,100,200,20);    
    b=new JButton("Find IP");  
    b.setBounds(50,150,80,30);  
    b.addActionListener(this);  
    add(l);  
    add(tf);  
    add(b);  
    setSize(300,300);  
    setLayout(null);  
    setVisible(true);  
}  
public void actionPerformed(ActionEvent e)
{  
    String url=tf.getText();   
    InetAddress ia=InetAddress.getByName(url);  
    String ip=ia.getHostAddress();  
    JOptionPane.showMessageDialog(this,ip);    
}  
public static void main()
{  
    new IPFinder();  
}
  }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Java Rookie
  • 432
  • 3
  • 12
  • 1
    Look at the documentation for [`getByName()`](https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName(java.lang.String)) and you will see that it can throw an `UnknownHostException`. Your code should handle that with a `try/catch` block. – 001 Sep 07 '17 at 14:49

1 Answers1

1

getByName() can throw an Exception. You must handle all possible exceptions by using try/catch blocks. Here is a tutorial on how to handle exceptions: https://docs.oracle.com/javase/tutorial/essential/exceptions/

jwils
  • 495
  • 3
  • 11