I am doing a method who return an UUID of a Minecraft player from his username using the Mojang API. This method takes a String in parameter (the username of the player who we want to know the UUID). To use the resultat of the API, I use the SimpleJSON library (to parse the JSON result into a String to return).
My method throws 2 checked exceptions : the IOExeption and the Parseexception, cause I want.
When a wrong username (so an username who doesn't exist) the API return a empty JSON object and my method throws an IOException in this case. And this is my problem, when a wrong username is in paramter of the method, the method throw a new IOExcpetion but with a try and catch for the method, the throwing exception isn't catched.
My method :
public static String getUUID(String name) throws IOException, ParseException {
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
URLConnection uc = url.openConnection();
BufferedReader bf = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = bf.readLine()) != null) {
response.append(inputLine);
}
bf.close();
if (response.toString().isEmpty()) {
throw new IOException();
}
JSONParser parser = new JSONParser();
Object object = parser.parse(response.toString());
JSONObject jo = (JSONObject) object;
String str = (String) jo.get("id");
return str.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
}
An example of using a valid username :
public static void main(String[] args) {
try {
System.out.println(getUUID("Jeb_"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
And now an example with a wrong username:
public static void main(String[] args) {
try {
System.out.println(getUUID("d"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
Thank you.
Have you verified that your exception might get caught? If it is caught, the code prints a stack trace. But if it is not caught, the JVM will print a stack trace anyway.
So throw the exception with some message you can verify, like
throw new IOException("Invalid user");
and catch the exception by being a bit more verbose:
catch (IOException | ParseException e) {
System.out.println("Could not lookup user "+username+", caught "+e.getClass().getName()+": "+e.getMessage());
}
Actually, your exception is caught, you can check it as follows:
public static void main(String[] args) {
var username = "d";
try {
System.out.println(getUUID(username));
} catch (IOException | ParseException e) {
System.out.println("User " + username + " not found!");
e.printStackTrace();
}
}
The output of the program will be:
User d not found!
java.io.IOException
at com.company.Main.getUUID(Main.java:37)
at com.company.Main.main(Main.java:17)
This output means that code inside catch block was executed.
Related
So I have a working ObjectOutputStream in a method that I start by calling the method in main. I need to then read the file it created and print out all 5 objects in it. Right now I'm only printing out the first object.
public static AccountSerializable serializReadObject() throws ClassNotFoundException, IOException {
AccountSerializable read = null;
try { // Create an input stream for file accounts.ser
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
read = (AccountSerializable) input.readObject();
input.close();
} catch (IOException i) {
throw i;
}catch(ClassNotFoundException c){
throw c;
}
return read;
}
public static void main(String[] args) {
try {
System.out.println(serializReadObject());
} catch (ClassNotFoundException | IOException e) {
System.out.println("Class not found");
e.printStackTrace();
}
}
I've tried to throw
boolean eof = false;
while(!eof){
try{
//read data
}catch(EOFException e){
eof = true;
}
}
in serializReadObject To loop it and I've also tried to instead catch it in main but I keep getting an error stating "Unreachable catch block for EOFException it is already handled by the catch block"
I then tried to take away the IOException and just put EOFEception but alas it keeps forcing me to surround my read with IOException. Is there another way to loop this with EOF?
You're only getting the first object because your opening and closing the stream on each call. There are many ways to achieve what you want. One way is to use a List<AccountSerializable>:
public static List<AccountSerializable> serializeReadObjects() throws IOException, ClassNotFoundException {
// create an input stream for file accounts.ser
// this line will throw an IOException if something goes wrong
// we don't need to catch it in this method though
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
// create list to hold read in accounts
List<AccountSerializable> accounts = new ArrayList<>();
// keep reading until EOFException is thrown
boolean keepReading = true;
while(keepReading) {
try {
// read in serialized account
AccountSerializable read = (AccountSerializable) input.readObject();
// add read in serialized account to the list
accounts.add(read);
} catch(EOFException eofe) {
// we are at the end of file, so stop reading
keepReading = false;
input.close();
} catch(IOException ioe) {
// input stream error other than EOF, not sure what to do
input.close();
throw ioe;
} catch(ClassNotFoundException cnfe) {
// not sure what to do in this case, so close input
input.close();
throw cnfe;
}
}
return accounts;
}
public static void main(String[] args) {
List<AccountSerializable> accounts = null;
try {
// get list of read in accounts
accounts = serializeReadObjects();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
// iterate over list of read in accounts and output them to stdout
for(AccountSerializable account : accounts) {
System.out.println(account);
}
}
Would this be problematic and run into issues?
Example:
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
try {
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (FileNotFoundException ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
}
If it is problematic, what other approach should I look to?
Too many try-catch would complicate code and reduce the code readability which will lead to swallowing an exception and its much more worse than performance issues as it can crash your system unexpectedly.
Here is an example of swallowing an exception and its side effects (multiple point of failures like NPE etc.).
public static void main(String[] args) {
String dataFromFile = null, dataFromDataBase = null;
try {
try {
dataFromFile = readFile();
} catch (IOException e) {
// ignore exception
// String dataFromFile will be set to null
// as there was an exception
}
// imagine many lines of code here
dataFromDataBase = readDatabase(dataFromFile.getKey());
} catch (IOException e) {
// ignore exception
}
// imagine many lines of code here
System.out.println(dataFromFile.replace(" ", ""));
//imagine many lines of code here
System.out.println(dataFromDataBase.getKey());
}
private static String readFile() throws IOException {
// throws ioexception
}
private static String readDatabase(String key) throws IOException {
// throws ioexception
}
If you are expecting multiple points in a single method that can throw exceptions then club them into one try-catch and handle them appropriately. Again there can be exception to this specific question but you should always try to reduce multiple try-catch in single method.
Unless you are doing something specific with an exception, use single Exception clause to handle all exception and log details or throw it to the caller to handle it in its own specific ways.
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (Exception ex) {
// Display Exception stuff details
}
}
In this example I see no reason to start a new try statement. why not do this?
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
But no, there would be no problem. it just looks bad. but sometimes needed I guess.
Could you help me understand where should I throw exceptions and catch them.
Please, have a look at my code. I thought that in Thrd class I have already thrown and caught the exception. But when I wrote in the main class FirstThread.readFile("ParallelProgramming.txt");, I faced a runtime error - unhandled exception. So, I had to use try and catch. So, I somehow can't understand why in the Thd class my try and catch blocks didn't work.
package parallelprogramming;
import java.lang.Thread;
import java.io.*;
public class Thrd extends Thread {
public void readFile(String File) throws FileNotFoundException {
FileReader fr = new FileReader(File);
BufferedReader br = new BufferedReader(fr);
String s;
try {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
catch (FileNotFoundException FNFD) {
System.out.println("File not found!");
}
catch (IOException IOE){
System.out.println("IOException caught!");
}
}
}
package parallelprogramming;
import java.io.FileNotFoundException;
public class ParallelProgramming {
public static void main(String[] args) throws FileNotFoundException {
Thrd FirstThread = new Thrd();
try {
FirstThread.readFile("ParallelProgramming.txt");
} catch (FileNotFoundException FNFD) {
System.out.println("File not found!");
}
}
}
The rules with checked exceptions (and this includes IOException, which FileNotFoundException is a child of), are as follows:
if you cannot, or do not want, to handle it in your current method, declare that the method throws it;
if you want to handle it in your current method, then catch it; note that even in this case you can rethrow that exception;
if main() throws any exception, and this exception triggers, the program terminates.
Now, we suppose that you are using Java 7. In this case, do that:
public void readFile(final String file)
throws IOException
{
final Path path = Paths.get(file);
for (final String line: Files.readAllLines(path, StandardCharsets.UTF_8))
System.out.println(line);
}
Why bother? ;)
If you don't want to do that but read line by line, then:
public void readFile(final String file)
throws IOException
{
final Path path = Paths.get(file);
try (
final BufferedReader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
}
}
The second form is preferred if you wish to treat exceptions specifically. Note that with Java 7, you have meaningful exceptions as to why you cannot access the file vs IOException: NoSuchFileException, AccessDeniedException, etc etc. All these inherit FileSystemException. The old file API can't do that for you.
This means that if you want to deal with filesystem level errors you can do:
catch (FileSystemException e) { /* ... */ }
where before that you did:
catch (FileNotFoundException e) { /* ... */ }
Translated to the code above, if you want to catch exceptions you'll then do:
// All exceptions handled within the method -- except if you rethrow it
public void readFile(final String file)
{
final Path path = Paths.get(file);
try (
final BufferedReader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
} catch (FileSystemException e) {
// deal with a filesystem-level error
// Note that you MUSt catch it before IOException
// since FileSystemException inherits IOException
} catch (IOException e) {
// deal with a low-level I/O error
}
}
Remove 'throws FileNotFoundException' from the readFile method of class Thrd then you dont need to handle this exception in main method of class ParallelProgramming.
As you throw FileNotFoundException from readFile method then exception will pass to the method will called this i.e. then main method need to handle this exception.
There are two ways to handle an exception either you need to catch it or throw it again.
In the readFile method you have done both. you caught the exceptions using catch blocks then you have mentioned that readFile method throws FileNotFoundException, so when ever you use readFile method you need to catch the exception again.
I've not been able to resolve the following exception in the code below. What is the problem with the way I use BufferedReader? I'm using BufferedReader inside the main method
OUTPUT :-
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);
//Return the last element in the array of strings
return parts[parts.length -1];
}
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
}
UPDATE :
The following works:
public static void main(String[] args) throws FileNotFoundException, IOException {
However try.. catch still has some nagging issues for me:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}
buffread dosent seem to get the file name. I get this error:
javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol
symbol : variable buffread
location: class ParseFileName
while ((line = buffread.readLine())!= null) {
Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).
i.e.
public static void main(String[] args) throws FileNotFoundException, IOException {
Alternately, if you'd like to catch a specific exception and do something with it:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}
Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.
BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...
You have to add throws statement into the signature of method main or wrap code in
try {
...
} catch (FileNotFoundException e) {
...
}
Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.
The BufferReader can throw an exception if the file cannot be found or opened correctly.
This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread;
try
{
buffread= new BufferedReader (new FileReader("file.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
Another option is to add "throws IOException" to your method header.
public static void main(String[] args) throws IOException {
//...
}
This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.
Follow on from an earlier question here. Trying to send this object Employee via HTTP. I'm not getting any errors but am hoping for a printout of the employee details at the other end but something isn't happening. I'm opening my log files to see the printout on my tomcat server but other than the indication that the method has started showing the START printout I'm not getting the END one. So something isn't working right in that section.
Here is the test class Employee:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Client Side:
public class SerializeAndSend {
public static void main(String args[]){
one.Employee e = new one.Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
sendObject(e);
}
public static Object sendObject(Object obj) {
URLConnection conn = null;
Object reply = null;
try {
// open URL connection
URL url = new URL("///myURL///");
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
// send object
ObjectOutputStream objOut = new ObjectOutputStream(conn.getOutputStream());
objOut.writeObject(obj);
objOut.flush();
objOut.close();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
// recieve reply
try {
ObjectInputStream objIn = new ObjectInputStream(conn.getInputStream());
reply = objIn.readObject();
objIn.close();
} catch (Exception ex) {
// it is ok if we get an exception here
// that means that there is no object being returned
System.out.println("No Object Returned");
if (!(ex instanceof EOFException))
ex.printStackTrace();
System.err.println("*");
}
return reply;
}
}
I think thats correct. But I'm stuck on the server end, I have the employee class on the server side too:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("START");
Object obj;
Employee emp = null;
ObjectInputStream objIn = new ObjectInputStream(req.getInputStream());
try {
obj = objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
emp = (Employee)objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("END");
System.out.println(emp.name);
}
Any ideas whats going wrong on the receiving end?
try {
obj = objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
emp = (Employee)objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
You are sending one object and trying to receive two. You either need this:
obj = objIn.readObject();
if (obj instanceof Employee)
{
Employee emp = (Employee)obj;
}
or this:
Employee emp = (Employee)objIn.readObject();
Not a mixture of both. Two readObject() calls implies reading the stream for two distinct objects, and you aren't sending them.
Secondly, you shouldn't catch Exception and then use instanceof on the exception object. In this case you should have a separate catch (EOFException exc), which is OK if you expect to receive zero objects, but not otherwise, and then catch the other possible exceptions separately: they are not OK.