Exceptions Java

1/0 is undefined, since it’s being divided by 0.


With 0/0, this is indeterminate, since anything can be multiplied by zero to get zero.


Exceptions


public FileReader(File file)
    throws FileNotFoundException// when it doesn't work, it will throw this error. 


When it comes to printing the error and the output, it is possible to have the error in two places: one where you would display the error with try-catch, and with printStackTrace, it might have times where part of the error is before ENDOFBLOCK, and other times, it was after ENDOFBLOCK.



Multiple Catches


Allowyou s to handle each specific exception

  • Do the necessary action accordingly

  • log it, or call a different function afterwards



It handles the general exception case; it should be the last one.


Do NOT clean the catch bloc.k

IT makes the JVe silent and just makes your code stuck.


An exception to this rule is malware, since it doesn’t really care what happens code-wise, since it’s just there to infect.


When it comes to errors and exceptions, errors are just like bad JVM ecceptions that can’t be fixed, like using more than 2mb (or gb,idk) of memory.


Example of Multiple catches


With this, the regular exceptions will say it isn’t reachable, the complier will say that, so, it will be a warning, but it will still compile.


If you do other things that produce exceptions, it would remove said warning in the code.



JAva’s some default


Some cases can throw exception buyt Java allows those not to be wrapped around try-catch.


This is called an unchecked exception.


IOException are checked. Developer must handle that.


If it is left to the developer to write a try-catch block.


int num = Integer.parseInt("JAVA");
// java.lang.NumberFormatException exception is unchecked



finally block(optional in try-catch)


With this, it will always execute, no matter what happens.


exit,If there is a return or a System. exit, it will still printfinallyy, NO matter what happens.

(It always executes the finally block, doesn’t matter if you exit the program early.


Why not use ifs?


Exceptions can be seen up the call stack, being able to be propagated, viewing the call stack and error message if we use Exceptions.


Also, with exceptions, you can retry an operation, log errors, or provide alternative behavior. Very annoying to do with if statements alone.


Also, Ifs can kill the readability of the main logic of the program, since try-catch is better used for catching exceptions, not if statements.


Writing our Own Exception


thrown,If an exception is tthrown it will return a exception.


Same for void functions, still can throw an exception, isn’t dependent on returning keywords(int, double, object, array, arraylist)

It does extends exception


With the thrower methods, it can either just run the previous thrower, or actually handle the excpetion.


In the end, it needs to have a try-catch for it.