Java Exceptions - try Catch

Java Exceptions Try Catch

Exception Handling In Java
  • Ever since the beginning of programming languages, error handling has been a particularly difficult issue.
  • Exception handling wires error handling directly into the programming language and sometimes even the operating system.
  • An exception is an object that is “thrown” from the site of the error and can be “caught” by an appropriate exception handler designed to handle that particular type of error.
Exception Handling key Points
  • Use try and catch
  • Know the members of Throwable
  • Use finally
  • Use throws etc.
  • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
  • Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a try block.
  •  If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner.
  • System-generated exceptions are automatically thrown by the Java run-time system.
  • To manually throw an exception, use the keyword throw.
  • Any exception that is thrown out of a method must be specified as such by a throws clause.
  • Any code that absolutely must be executed after a try block completes is put in a finally block.
This is the general form of an exception-handling block-
try {
// block of code to monitor for errors
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
// ...
finally {
// block of code to be executed after try block ends
Example - ArithmeticException generated by the division-by-zero error
Output -
We saw the exception occurrence in the previous example now we will deal with this with the help of an exception handling 
Example- # ArithmeticException generated by the division-by-zero error using try-catch 
Output - 
Example -
Output -