needn't to catch the exception in the realization of System.out? - java

I am new to java, and to make clear of "System.out", i read relevant java source code, then find something i cannot understand.
First the source code of "System.out":
public final static PrintStream out = nullPrintStream();
then i went to nullPrintStream
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
My question is: the program may throw a NullPointerException in the function nullPrintStream(), and we needn't to catch the exception in public final static PrintStream out = nullPrintStream();? To make clear of it, i wrote some test codes in Eclipse as follows:
package MainPackage;
public class Src {
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new Exception();
}
return 0;
}
public static final int aTestObject = throwException(); <==Here i got an error
public static void main(String args[]) {
}
}
Just like i think, i got an error Unhandled exception type Exception, but why System.out is OK without doing with the NullPointerException?

Java has a special class of Exceptions called RuntimeExceptions. They all extend the RuntimeException object, which in turn extends the Exception object. The special thing about a RuntimeException (as opposed to a regular exception) is that it does not need to be explicitly thrown. Several different exceptions fit into this category, such as IllegalArgumentException, IllegalStateException etc...
The advantage of using RTE when you are coding is that you do not need to cover your code with a lot of try/catch/throws statements, especially if the exceptions are expected to be extremely rare and unlikely. Additionally, if you have a general mechanism in place for catching RTE, this will also help make sure your app deals with expection conditions cleanly.
That being said, RTEs can be much more difficult to deal with, as it is not obvious from the signature that a particular class or method will throw that type of exception. Consequently, they are not always a good idea for APIs, unless they are well documented.
A NullPointerException is a RuntimeException, and consequently, does not need to be explicitly declared in the method signature.

NullPointerException is a RuntimeException - it doesn't need to be explicitly caught.
if you make your method do this, it won't bomb on compile:
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new RuntimeException();
}
return 0;
}

if i adhere to throw Exception() in private static int throwException() , how should i modify public static final int aTestObject = throwException();
You can need to intialise the value in a static block and catch the exception there.
public static final int aTestObject;
static {
try {
aTestObject = throwException(); <==Here i got an error
} catch (Exception e) {
throw new AssertionError(e);
}
}

Related

Accessing field in super to report error

I'm not great with java terminology so it will be easier for you to understand via example:
I instantiate a mymethods class from a
Main class:
public class Main()
{
public boolean hasErrors = false;
MyMethods m = new MyMethods(); //cannot use try/catch
public static void main(String[] args){
m.writeToFile("text");
}
}
In the above class, i cannot (i tried) use a try catch to catch a manually thrown FileNotFoundException but apparently such methods cannot be used in that location (wrapping MyMethods m... in try/catch). I had tried to throw that error when my requisite file wasnt found
MyMethods:
public class MyMethods()
{
public MyMethods(){
if(!new File("file.txt").canWrite()){
changeSuper(true);
throw new FileNotFoundException();
}
}
public void changeSuper(boolean b) //does not work
{
super.hasErrors = b;
}
//input more methods etc here
}
Why is it not possible to use try/catch?
How can i report a filenotfound to the main method?
Note that this is from a GUI app in netbeans, but is not the focus here. Program will not compile if try/catch wraps that line
(note to admins/mods: this question needs butchering, but I cannot express my question better myself)
You just need to add the throws keyword to your method, i.e:
public static void myMethod() throws FileNotFoundException{
// Code goes here ...
if( fileNotFound )
throw new FileNotFoundException("File not found.");
}
you can then catch the exception by surrounding your call to the method with a try/catch block:
try {
// Do stuff...
myMethod();
} catch (FileNotFoundException ex){
// Handle error, if thrown...
}

Catching an ArithmeticException but not handling as intended

I am kinda new with the whole catching-handling exceptions concept and I was wondering why the throws ArithmeticException doesn't produce an exception error message (in this case/by zero) on exit, but instead during compilation.
Shouldn't it compile normally and then show the error message at the screen? What am I doing wrong?
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}
I executed your code as it is
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}
And it compiles fine without any error or exception, and as per your requirement, it is throwing ArithmeticException at run time only when System.out.println("Div: "+(a/b)); statement is encountered.
So I don't See any Problem there!
Checked Exception : these exception will throw error while compilation if you have not handled these exceptions.
Unchecked Exception : you will get error only at RunTime if you have not handled.
ArithmaticException is unchecked exception so you will get exception at runtime.
if you are using try-catch block then you have to use
printStackTrace()
method to print exception stack trace.
as :
try{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
catch(ArithmeticException e){
e.printStackTrace();
}
Take a look at the following picture:
As you can see a few of the exception classes are in a bold font to draw our attention to them. Here is the editors explanations about these categories of exceptions
Conditions that can readily occur in a correct program are checked exceptions. Concretely these kind of exceptions are <> by the compiler and he can correctly assess the eventuality of their occurence and declare a compilation error when the circumstances correspond to it. As you can see from the picture, NullPointerException is not directly under this category: these are the exception that directly extends the Exception class.
Severe problems that normally are treated as fatal or situations that probably reflect program bugs are unchecked exceptions.
Fatal situations are represented by the Error class.
Probable bugs are represented by the RuntimeException class. This is the case for exemple with the exceptions that extends the RuntimeException class. NullPointerException is one of them. In most of the cases of this kind of exception the compiler is not able to assess #compile time that they will cause an exception, since there is a strong dependency to the dynamic state of the application
Here is a simple illustration:
I have created two exceptions classes one that extends Exception
public class Exception1 extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
and one that extends RuntimeException
public class Exception2 extends RuntimeException {
private static final long serialVersionUID = 4595191052237661216L;
}
Then I have the following NewTester class
public class NewTester {
public static void methodA() throws Exception1 {
throw new Exception1();
}
public static void methodB() throws Exception2 {
throw new Exception2();
}
public static void main(String[] args) {
// methodA();
methodB();
}
}
I have purposefully commented the call to methodA.In this state you don't have any compilation error because the method that is called methodBthrows a RuntimeException which is unchecked. But if you would change this code by uncommenting the call to methodA and commenting the call to methodB you will have a compilation error, because methodA throws a checked exception
I hope this helps

Optional exception catching

Is it possible to make an exception that is optional to be caught?
In other words, an exception that can either:
be caught in a try-catch block
or skipped if no try-catch block exists for it
To visualize, I have a ReportedException, which is just a plain subclass of RuntimeException, and want to be able to catch it when it's needed:
try
{
hideWindow();
}
catch (ReportedException ex)
{
// Window could not be hidden.
// Exception has already been caught and logged by parseInput(),
// and now we're going to do something more.
printAdditionalErrorMessage();
}
Note: I edited the above example to better fit my question.
or skip catching if the result is irrelevant:
hideWindow(); // We don't care if there was an error or not.
openAnotherWindow();
I know I can leave the catch block empty and have the same thing as above, but I use ReportedException very often and it would make my code highly unreadable.
If it's impossible (I suspect it is), what alternative/walkaround would you recommend?
P.S. The method names used in the examples are just foo's and bar's.
EDIT: I know I don't need to catch RuntimeExceptions. What I want is to ignore them if they occur.
Exceptions should be used for exceptional situations.
From your example, if the window not being hidden is a typical event, it shouldn't throw an exception. If that is your function, then use a return value to indicate whether it was successful instead of throwing an exception. Then you can safely ignore the return value when you don't care if it succeeded or not.
If you do not have control over that method, then you can wrap it in another method that catches the exception and turns it into a return value. E.g.
private boolean tryHideWindow() {
try {
hideWindow();
}
catch (ReportedException ex) {
return false;
}
return true;
}
If you need some parameters of the exception to determine what to do, then you could return the exception instead.
private static class MyReturnType {
private final Throwable thrown;
private final OrigRtnType returnVal;
public MyReturnType(Throwable thrown) {
this.thrown = thrown;
this.returnVal = null;
}
public MyReturnType(OrigRtnType returnVal) {
this.thrown = null;
this.returnVal = returnVal
}
public boolean wasExceptionThrown() {
return thrown != null;
}
}
private MyReturnType tryHideWindow() {
try {
OrigRtnType returnVal = hideWindow();
}
catch (ReportedException ex) {
return new MyReturnType(ex);
}
return new MyReturnType(returnVal);
}
This is an answer to your question, but it is not necessarily a good idea. As others will doubless comment, using exceptions for program flow is less than ideal.
I'm a little fuzzy on how to use ThreadLocal (and there are apt to be some other tupos), but something like this:
public class IgnorableException {
static class DontIgnoreCount {
int count;
}
// Thread local variable containing each thread's ID
private static final ThreadLocal<DontIgnoreCount> dontIgnoreCount =
new ThreadLocal<DontIgnoreCount>();
static void incrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
if (counter == null) {
counter = new DontIgnoreCount();
dontIgnoreCount.set(counter);
}
counter.count++;
}
static void decrementDontIgnore() {
DontIgnoreCount counter = dontIgnoreCount.get();
// Must not be null here
counter.count--;
static bool shouldSignal() {
DontIgnoreCount counter = dontIgnoreCount.get();
return counter.count > 0;
}
}
To use, invoke DontIgnoreCount.incrementIgnoreCount() early in try range, and DontIgnoreCount.decrementIgnoreCount() late in finally range.
When signalling an exception that follows this protocol, only signal it if shouldSignal returns true.
void iWannaCatchException() {
try {
IgnornableException.incrementDontIgnore();
int x = someOptionallySignallingMethod();
}
catch (...) {
...
}
finally {
IgnorableException.decrementDontIgnore();
}
}
void iDontWannaCatchException() {
int x = someOptionallySignallingMethod();
}
int someOptionallySignallingMethod() {
if (somethingBad) {
if (IgnorableException.shouldSignal()) {
throw new BadException();
}
}
return 42;
}
Note that not shown above are any throws clauses you'd have to add to keep the compiler happy. This mechanism would not remove the need for those.
You could also inplement a delegate/observer scheme, replacing the simple counter with a stack of observer objects, and pass a message to the observer vs throwing the exception. But this, by itself (without coupled exceptions/try ranges) would not allow blowing away the stack to the appropriate recovery point.
It sounds like you want to use exceptions for flow control, rather than for reporting truly exceptional cases.
Using exceptions for flow control is typically frowned upon. The common approach is to return a success/failure indication as the return value of the function.
You can use something like this:
try{
hideWindow();
}catch (ReportedException ex){
// ingore
}catch (NullPointerException ex){
killWindow();
}finally {
//to do something more.
}

Java unhandled file type on object constructor

I'm trying to have the file "TutorialMap" used as the map in this TutorialMission. I keep getting told that the MapReader "reader" needs to be static, but when it's static, I get told "Unhandled exception type FileNotFoundException" with the error on the constructor of reader.
static MapReader reader = new MapReader("TutorialMap");
static Territory[][] missionMap = reader.getMap();
public TutorialMission() throws FileNotFoundException {
super(missionMap, Size, AircraftCarrierID, AircraftCarrierID);
}
The Super class' constructor:
public class MissionIF extends Map {
public MissionIF(Territory[][] load, String size, int StartingMoney, int powerLevel)
{
// Set money per mission.
super();
Thanks for your time.
I don't know why it must be static, but since the constructor throws the checked exception, it has to be handled at the place of calling. Therefore do something like this:
static MapReader reader = null;
static Territory[][] missionMap = null;
static {
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
e.printStackTrace();
}
missionMap = reader.getMap();
}
Compiler requires your reader to be static because you invoke it when initializing other static variable missionMap.
When you mark it as static compiler is going forward and sees that you do not catch exception thrown from your constructor TutorialMission.
Since I do not understand what do you really want to do I can just suggest you:
If you want all this stuff to be static initialize reader into static initializer and catch exception:
static MapReader reader;
static {
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
}
Your checked exception is now wrapped by unchecked one.
Alternatively (if you do not really want to hold this data in static variables just remove static modifier and perform initalization in constructor:
public TutorialMission(MapReader reader, Territory[][] missionMap) throws FileNotFoundException {
super(missionMap, Size, AircraftCarrierID, AircraftCarrierID);
missionMap = reader.getMap();
}
Now caller is responsible on creating and passing here the reader.
surrounds the code throwing "Unhandled exception type FileNotFoundException" with try catch block. Your are getting this exception because its a checked exception and you are forced to handle this. i would suggest using IDE like eclipse(if you are not using this already) which is really helpful for development.
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
throw new RunTimeException(e);
}

Trouble with a thread-safe queue class. Specifically, with exceptions

I am using a thread-safe queue class and have a problem with the insert method I've defined. A Buffer stores an array (elementData) that uses the start/end variables to know where to add/delete stuff from the queue. It's thread-safe, so it uses synchronized methods so I can have multiple threads refer to the same buffer.
public class Buffer<T> {
private T[] elementData;
private int elementCount;
private int start;
private int end;
// Additional fields
// Code to instantiate a Buffer, other methods (e.g. delete)
public synchronized void insert(T t) throws InterruptedException {
while (elementCount == elementData.length) {
wait();
}
end = (end + 1) % elementData.length;
elementData[end] = t;
elementCount++;
notifyAll();
}
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
b.insert(3);
}
}
Here's my understanding of the situation. When a method such as insert is called, we want to be able to throw an exception that could happen when the main method or some other thread gets called and tries to perform insert while it's suspended. But what I don't understand is why I get this unreported exception. I thought that having a "throws InterruptedException" after the method would be sufficient. Do I need a "try" block? My attempts with try blocks have all failed, so I'm a little stumped as to how to fix this error.
Also, I'm aware that I don't have any actual threads running. I'll do those once I can fix this unreported exception. :) Thanks to anyone who can help.
Buffer.java:56: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
b.insert(3);
The compile exception is because your insert method could throw an InterruptedException (even if you're not throwing it on purpose), so every method that calls it must use a try/catch block, even if the error never arises:
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
try {
b.insert(3);
} catch(InterruptedException ie) {
//error handling
e.printStackTrace();
}
}

Categories