I was trying to find out a way to handle Exceptions without using a bunch of try and catch blocks and I came across something quite handy.
This can be very useful if your server randomly disconnects, has random lags, random uncaught exceptions, etc. It can help you find the cause of the exceptions, write them to a file, or even handle them directly.
Firstly, you need to go to your Main class, in my case (z508) , it's Server.java
Somewhere in your main method, add this.
Code:
Thread.setDefaultUncaughtExceptionHandler(new ServerExceptionHandler());
Now make a new class called ServerExceptionHandler and put this in it:
Code:
package net.com.codeusa;//Obviously, you are going to have to change.
import java.io.*;//I don't like importing, and I wasn't using Eclipse atm.
import java.util.*;
import java.lang.*;
import java.text.*;
import java.lang.Thread.UncaughtExceptionHandler;
/*
* Written by Scary Kidz from Rune-Server
*/
public class ServerExceptionHandler implements UncaughtExceptionHandler {
public void uncaughtException(Thread thread, Throwable throwable) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("E MM/dd/yyyy 'at' hh:mm:ss a zzz");
String t = sdf.format(cal.getTime());
throwable.printStackTrace();
System.out.println("Unhandled exception, logging it now..");
try {
FileWriter fileStream=new FileWriter("./data/Exceptions.txt",true);
PrintWriter printWriter = new PrintWriter(fileStream);
printWriter.println(t);
throwable.printStackTrace(printWriter);
printWriter.println();
printWriter.flush();
printWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
//Currently just writes the Exceptions to a log. If you want to handle it, or do whatever, do it here. Note - this doesn't include try and catch blocks.
}
}
Put it anywhere you want, just make sure you import it properly in your Main class.
You can add..
Code:
Thread.setDefaultUncaughtExceptionHandler(new ServerExceptionHandler());
To any threads in your server.
I'm not sure if this is already implemented in any servers, I know Hyperion has a special logging system. I know it's common knowledge to a lot of people, but I've never seen it around, so hopefully it helps someone. If you use this, I wouldn't some feedback. If you have any tips on how to improve it, post 'em here and I might add it to the main post.