Use multiple catch, try-with-resources, replace system.out and e.printStackTrace

This commit is contained in:
mezz 2017-06-27 22:56:54 -07:00
parent 10ca404e9e
commit 93025510ae
27 changed files with 62 additions and 132 deletions

View file

@ -34,6 +34,8 @@ import net.minecraftforge.event.CommandEvent;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.FMLLog;
import static net.minecraft.util.text.TextFormatting.*;
/**
@ -109,7 +111,7 @@ public class ClientCommandHandler extends CommandHandler
catch (Throwable t)
{
sender.sendMessage(format(RED, "commands.generic.exception"));
t.printStackTrace();
FMLLog.log.error("Command '{}' threw an exception:", message, t);
}
return -1;

View file

@ -575,12 +575,7 @@ public class ModelBlockAnimation
//String json = mbaGson.toJson(mba);
return mba;
}
catch(IOException e)
{
FMLLog.log.error("Exception loading vanilla model animation {}, skipping", armatureLocation, e);
return defaultModelBlockAnimation;
}
catch(JsonParseException e)
catch(IOException | JsonParseException e)
{
FMLLog.log.error("Exception loading vanilla model animation {}, skipping", armatureLocation, e);
return defaultModelBlockAnimation;

View file

@ -182,11 +182,7 @@ public enum KeyModifier {
{
return valueOf(stringValue);
}
catch (NullPointerException ignored)
{
return NONE;
}
catch (IllegalArgumentException ignored)
catch (NullPointerException | IllegalArgumentException ignored)
{
return NONE;
}

View file

@ -234,7 +234,7 @@ public class DimensionManager
}
catch (Exception e)
{
System.err.println("Cannot Hotload Dim: " + e.getMessage());
FMLLog.log.error("Cannot Hotload Dim: {}", dim, e);
return; // If a provider hasn't been registered then we can't hotload the dim
}
MinecraftServer mcServer = overworld.getMinecraftServer();
@ -348,7 +348,7 @@ public class DimensionManager
}
catch (MinecraftException e)
{
e.printStackTrace();
FMLLog.log.error("Caught an exception while saving all chunks:", e);
}
finally
{

View file

@ -421,7 +421,7 @@ public class ForgeModContainer extends DummyModContainer implements WorldAccessC
}
catch (Exception e)
{
e.printStackTrace();
log.error("Could not find class for name '{}'.", name, e);
}
}

View file

@ -124,7 +124,7 @@ public class MinecraftForge
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Could not find class for name '{}'.", name, e);
}
}
}

View file

@ -64,9 +64,7 @@ public enum CapabilityManager
{
try {
return implementation.newInstance();
} catch (InstantiationException e) {
throw Throwables.propagate(e);
} catch (IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException e) {
throw Throwables.propagate(e);
}
}

View file

@ -26,6 +26,7 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.ChunkPos;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkDataEvent;
import net.minecraftforge.fml.common.FMLLog;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
@ -69,7 +70,7 @@ class ChunkIOProvider implements Runnable
}
catch (IOException e)
{
e.printStackTrace();
FMLLog.log.error("Failed to load chunk async.", e);
}
if (data != null)

View file

@ -50,6 +50,7 @@ import java.util.regex.Pattern;
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Floats;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
@ -132,8 +133,7 @@ public class Configuration
File fileBak = new File(file.getAbsolutePath() + "_" +
new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".errored");
FMLLog.log.fatal("An exception occurred while loading config file {}. This file will be renamed to {} " +
"and a new config file will be generated.", file.getName(), fileBak.getName());
e.printStackTrace();
"and a new config file will be generated.", file.getName(), fileBak.getName(), e);
file.renameTo(fileBak);
load();
@ -1047,7 +1047,7 @@ public class Configuration
}
catch (IOException e)
{
e.printStackTrace();
FMLLog.log.error("Error while loading config.", e);
}
finally
{
@ -1108,7 +1108,7 @@ public class Configuration
}
catch (IOException e)
{
e.printStackTrace();
FMLLog.log.error("Error while saving config.", e);
}
}
@ -1712,11 +1712,12 @@ public class Configuration
prop.setMaxValue(maxValue);
try
{
return Float.parseFloat(prop.getString()) < minValue ? minValue : (Float.parseFloat(prop.getString()) > maxValue ? maxValue : Float.parseFloat(prop.getString()));
float parseFloat = Float.parseFloat(prop.getString());
return Floats.constrainToRange(parseFloat, minValue, maxValue);
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Failed to get float for {}/{}", name, category, e);
}
return defaultValue;
}

View file

@ -162,7 +162,7 @@ public final class AnimationStateMachine implements IAnimationStateMachine
}
else
{
System.out.println("Unknown special event \"" + event.event() + "\", ignoring");
FMLLog.log.error("Unknown special event \"{}\", ignoring.", event.event());
}
}
}
@ -230,12 +230,7 @@ public final class AnimationStateMachine implements IAnimationStateMachine
//System.out.println(location + ": " + json);
return asm;
}
catch(IOException e)
{
FMLLog.log.error("Exception loading Animation State Machine {}, skipping", location, e);
return missing;
}
catch(JsonParseException e)
catch(IOException | JsonParseException e)
{
FMLLog.log.error("Exception loading Animation State Machine {}, skipping", location, e);
return missing;

View file

@ -159,7 +159,7 @@ public class EnumHelper
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Error setting up EnumHelper.", e);
}
isSetup = true;
@ -385,8 +385,8 @@ public class EnumHelper
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
FMLLog.log.error("Error adding enum with EnumHelper.", e);
throw new RuntimeException(e);
}
}

View file

@ -108,7 +108,6 @@ import net.minecraftforge.fml.common.toposort.ModSortingException;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.registries.GameData;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.LWJGLUtil;
@ -300,17 +299,12 @@ public class FMLClientHandler implements IFMLSidedHandler
Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader());
String optifineVersion = (String) optifineConfig.getField("VERSION").get(null);
Map<String,Object> dummyOptifineMeta = ImmutableMap.<String,Object>builder().put("name", "Optifine").put("version", optifineVersion).build();
InputStream optifineModInfoInputStream = getClass().getResourceAsStream("optifinemod.info");
try
try (InputStream optifineModInfoInputStream = getClass().getResourceAsStream("optifinemod.info"))
{
ModMetadata optifineMetadata = MetadataCollection.from(optifineModInfoInputStream, "optifine").getMetadataForId("optifine", dummyOptifineMeta);
optifineContainer = new DummyModContainer(optifineMetadata);
FMLLog.log.info("Forge Mod Loader has detected optifine {}, enabling compatibility features", optifineContainer.getVersion());
}
finally
{
IOUtils.closeQuietly(optifineModInfoInputStream);
}
}
catch (Exception e)
{

View file

@ -148,21 +148,15 @@ public class SplashProgress
if (!parent.exists())
parent.mkdirs();
FileReader r = null;
config = new Properties();
try
try (FileReader r = new FileReader(configFile))
{
r = new FileReader(configFile);
config.load(r);
}
catch(IOException e)
{
FMLLog.log.info("Could not load splash.properties, will create a default one");
}
finally
{
IOUtils.closeQuietly(r);
}
//Some system do not support this and have weird effects so we need to detect and disable by default.
//The user can always force enable it if they want to take the responsibility for bugs.
@ -191,20 +185,14 @@ public class SplashProgress
File miscPackFile = new File(Minecraft.getMinecraft().mcDataDir, getString("resourcePackPath", "resources"));
FileWriter w = null;
try
try (FileWriter w = new FileWriter(configFile))
{
w = new FileWriter(configFile);
config.store(w, "Splash screen properties");
}
catch(IOException e)
{
FMLLog.log.error("Could not save the splash.properties file", e);
}
finally
{
IOUtils.closeQuietly(w);
}
miscPack = createResourcePack(miscPackFile);
@ -240,7 +228,7 @@ public class SplashProgress
}
catch (LWJGLException e)
{
e.printStackTrace();
FMLLog.log.error("Error starting SplashProgress:", e);
disableSplash(e);
}
@ -537,7 +525,7 @@ public class SplashProgress
}
catch (LWJGLException e)
{
e.printStackTrace();
FMLLog.log.error("Error setting GL context:", e);
throw new RuntimeException(e);
}
glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1);
@ -564,7 +552,7 @@ public class SplashProgress
}
catch (LWJGLException e)
{
e.printStackTrace();
FMLLog.log.error("Error releasing GL context:", e);
throw new RuntimeException(e);
}
finally
@ -629,7 +617,7 @@ public class SplashProgress
}
catch (LWJGLException e)
{
e.printStackTrace();
FMLLog.log.error("Error setting GL context:", e);
throw new RuntimeException(e);
}
}
@ -650,7 +638,7 @@ public class SplashProgress
}
catch (LWJGLException e)
{
e.printStackTrace();
FMLLog.log.error("Error releasing GL context:", e);
throw new RuntimeException(e);
}
lock.unlock();
@ -672,7 +660,7 @@ public class SplashProgress
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Error finishing SplashProgress:", e);
disableSplash(e);
}
}
@ -719,10 +707,8 @@ public class SplashProgress
enabled = false;
config.setProperty("enabled", "false");
FileWriter w = null;
try
try (FileWriter w = new FileWriter(configFile))
{
w = new FileWriter(configFile);
config.store(w, "Splash screen properties");
}
catch(IOException e)
@ -730,10 +716,6 @@ public class SplashProgress
FMLLog.log.error("Could not save the splash.properties file", e);
return false;
}
finally
{
IOUtils.closeQuietly(w);
}
return true;
}
@ -837,7 +819,7 @@ public class SplashProgress
}
catch(IOException e)
{
e.printStackTrace();
FMLLog.log.error("Error reading texture from file: {}", location, e);
throw new RuntimeException(e);
}
finally

View file

@ -41,6 +41,7 @@ import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.PostConfigChangedEvent;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.Event.Result;
@ -344,7 +345,7 @@ public class GuiConfig extends GuiScreen
}
catch (Throwable e)
{
e.printStackTrace();
FMLLog.log.error("Error performing GuiConfig action:", e);
}
if (flag)

View file

@ -128,8 +128,7 @@ public class GuiConfigEntries extends GuiListExtended
}
catch (Throwable e)
{
FMLLog.log.fatal("There was a critical error instantiating the custom IConfigEntry for config element {}.", configElement.getName());
e.printStackTrace();
FMLLog.log.error("There was a critical error instantiating the custom IConfigEntry for config element {}.", configElement.getName(), e);
}
else if (configElement.isProperty())
{

View file

@ -33,6 +33,7 @@ import net.minecraft.util.text.TextFormatting;
import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR;
import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
import net.minecraftforge.fml.common.FMLLog;
import org.lwjgl.input.Keyboard;
/**
@ -128,7 +129,7 @@ public class GuiEditArray extends GuiScreen
}
catch (Throwable e)
{
e.printStackTrace();
FMLLog.log.error("Error performing GuiEditArray action:", e);
}
this.mc.displayGuiScreen(this.parentScreen);
}

View file

@ -30,6 +30,7 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.FMLLog;
import static net.minecraftforge.fml.client.config.GuiUtils.RESET_CHAR;
import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
@ -128,7 +129,7 @@ public class GuiSelectString extends GuiScreen
}
catch (Throwable e)
{
e.printStackTrace();
FMLLog.log.error("Error performing GuiSelectString action:", e);
}
this.mc.displayGuiScreen(this.parentScreen);
}

View file

@ -700,11 +700,7 @@ public class FMLCommonHandler
task.run();
task.get(); // Forces the exception to be thrown if any
}
catch (InterruptedException e)
{
FMLLog.log.fatal("Exception caught executing FutureTask: {}", e.toString(), e);
}
catch (ExecutionException e)
catch (InterruptedException | ExecutionException e)
{
FMLLog.log.fatal("Exception caught executing FutureTask: {}", e.toString(), e);
}

View file

@ -320,15 +320,10 @@ public class FMLModContainer implements ModContainer
if (propsFile.exists() && propsFile.isFile())
{
version = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
try
try (FileInputStream fis = new FileInputStream(propsFile))
{
version.load(fis);
}
finally
{
IOUtils.closeQuietly(fis);
}
}
}
return version;

View file

@ -41,6 +41,7 @@ import static org.objectweb.asm.Type.BOOLEAN_TYPE;
import static org.objectweb.asm.Type.getMethodDescriptor;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.eventhandler.Event;
import org.objectweb.asm.ClassReader;
@ -92,7 +93,7 @@ public class EventSubscriptionTransformer implements IClassTransformer
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Error building events.", e);
}
return bytes;

View file

@ -430,7 +430,7 @@ public class FMLDeobfuscatingRemapper extends Remapper {
}
catch (IOException e)
{
e.printStackTrace();
FMLLog.log.error("Error getting patched resource:", e);
}
}
public void mergeSuperMaps(String name, @Nullable String superName, String[] interfaces)

View file

@ -46,25 +46,17 @@ public class JarDiscoverer implements ITypeDiscoverer
{
List<ModContainer> foundMods = Lists.newArrayList();
FMLLog.log.debug("Examining file {} for potential mods", candidate.getModContainer().getName());
JarFile jar = null;
try
try (JarFile jar = new JarFile(candidate.getModContainer()))
{
jar = new JarFile(candidate.getModContainer());
ZipEntry modInfo = jar.getEntry("mcmod.info");
MetadataCollection mc = null;
if (modInfo != null)
{
FMLLog.log.trace("Located mcmod.info file in file {}", candidate.getModContainer().getName());
InputStream inputStream = jar.getInputStream(modInfo);
try
try (InputStream inputStream = jar.getInputStream(modInfo))
{
mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName());
}
finally
{
IOUtils.closeQuietly(inputStream);
}
}
else
{
@ -83,15 +75,10 @@ public class JarDiscoverer implements ITypeDiscoverer
ASMModParser modParser;
try
{
InputStream inputStream = jar.getInputStream(ze);
try
try (InputStream inputStream = jar.getInputStream(ze))
{
modParser = new ASMModParser(inputStream);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
candidate.addClassEntry(ze.getName());
}
catch (LoaderException e)
@ -117,10 +104,6 @@ public class JarDiscoverer implements ITypeDiscoverer
{
FMLLog.log.warn("Zip file {} failed to read properly, it will be ignored", candidate.getModContainer().getName(), e);
}
finally
{
IOUtils.closeQuietly(jar);
}
return foundMods;
}

View file

@ -116,7 +116,7 @@ public class EventBus implements IEventExceptionHandler
}
catch (NoSuchMethodException e)
{
;
FMLLog.log.error("Could not find method '{}' on class '{}'", method.getName(), cls);
}
}
}
@ -160,7 +160,7 @@ public class EventBus implements IEventExceptionHandler
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Error registering event handler: {} {} {}", owner, eventType, method, e);
}
}

View file

@ -62,7 +62,7 @@ public class FMLDeobfTweaker implements ITweaker {
catch (Exception e)
{
// Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here
System.out.println("A CRITICAL PROBLEM OCCURRED INITIALIZING MINECRAFT - LIKELY YOU HAVE AN INCORRECT VERSION FOR THIS FML");
FMLLog.log.fatal("A CRITICAL PROBLEM OCCURRED INITIALIZING MINECRAFT - LIKELY YOU HAVE AN INCORRECT VERSION FOR THIS FML");
throw new RuntimeException(e);
}
}

View file

@ -127,14 +127,9 @@ public class GenDiffSet {
return new byte[0];
}
InputStream sourceZipInputStream = sourceZip.getInputStream(entry);
try
try (InputStream sourceZipInputStream = sourceZip.getInputStream(entry))
{
return ByteStreams.toByteArray(sourceZipInputStream);
}
finally
{
IOUtils.closeQuietly(sourceZipInputStream);
}
}
}

View file

@ -27,6 +27,7 @@ import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityList.EntityEggInfo;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.registries.IForgeRegistryEntry.Impl;
public class EntityEntry extends Impl<EntityEntry>
@ -79,7 +80,7 @@ public class EntityEntry extends Impl<EntityEntry>
}
catch (Exception e)
{
e.printStackTrace();
FMLLog.log.error("Error creating entity.", e);
return null;
}
}

View file

@ -312,10 +312,10 @@ public class CoreModManager {
Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re, "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided.");
File crashreportfile = new File(new File(coreMods.getParentFile(),"crash-reports"),String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tH.%1$tM.%1$tS.txt",Calendar.getInstance()));
crashreportclass.getMethod("a",File.class).invoke(crashreport, crashreportfile);
System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# " + crashreportfile.getAbsolutePath());
FMLLog.log.fatal("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# {}", crashreportfile.getAbsolutePath());
} catch (Exception e)
{
e.printStackTrace();
FMLLog.log.fatal("#@!@# FML has crashed while generating a crash report, please report this. #@!@#", e);
// NOOP - hopefully
}
throw re;
@ -466,19 +466,12 @@ public class CoreModManager {
try
{
Files.createParentDirs(target);
FileOutputStream targetOutputStream = null;
InputStream jarInputStream = null;
try
{
targetOutputStream = new FileOutputStream(target);
jarInputStream = jar.getInputStream(jarEntry);
try (
FileOutputStream targetOutputStream = new FileOutputStream(target);
InputStream jarInputStream = jar.getInputStream(jarEntry);
){
ByteStreams.copy(jarInputStream, targetOutputStream);
}
finally
{
IOUtils.closeQuietly(targetOutputStream);
IOUtils.closeQuietly(jarInputStream);
}
FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath());
result.put(dep,target);
} catch (IOException e)