Full Transcript

JAVA EXCEPTIONS Java Exceptions When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong inpu...

JAVA EXCEPTIONS Java Exceptions When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error). Java try and catch • The try statement allows you to define a block of code to be tested for errors while it is being executed. • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. • The try and catch keywords come in pairs Syntax try { // Block of code to try } catch(Exception e) { // Block of code to handle errors } Finally The finally statement lets you execute code, after try...catch, regardless of the result: The throw keyword The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc: If age was 20, you would not get an exception:

Use Quizgecko on...
Browser
Browser