Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Optimizationally, I think you're going to find it's probably a wash. They'll both perform alright, I don't think exception throwing is ever going to be your bottleneck. You should probably be more concerned with what Java is designed to do (and what other Java programmers will expect) and that is thrown exceptions. Java is very much designed around throwing/catching exceptions and you can bet the designers made that process as efficient as possible.</p> <p>I think it's mostly a philosophy and language culture sort of thing. In Java, the general accepted practice is that the method signature is a contract between your method and the code calling it. So if you receive an improper value, you generally throw an unchecked exception and let it be dealt with at a higher level:</p> <pre><code>public void setAge(int age) { if(age &lt; 0) { throw new IllegalArgumentException("Array can't be negative"); } this.age = age; } </code></pre> <p>In this case, the caller broke their end of the contract, so you spit their input back at them with an exception. The "throws" clause is for use when you can't fulfill your end of the contract for some reason.</p> <pre><code>public void readFile(String filename) throws IOException { File myfile = new File(filename); FileInputStream fis = new FileInputStream(myfile); //do stuff fis.read(); //do more stuff } </code></pre> <p>In this case, as the method writer, you've broken your end of the contract because the user gave you valid input, but you couldn't complete their request due to an IOException.</p> <p>Hope that kinda puts you on the right track. Good luck!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload