An Exception is a special object that describes an error or unexpected behavior of a script. We use them when
we want to safely stop or redirect code execution if we encounter a problem that the program cannot automatically
handle. We trigger an exception using the throw statement, and we catch it using a
try...catch structure, resolving it in time to prevent the entire webpage from crashing.
When we catch an exception inside a catch block, we gain access to an object that contains precise
data about where and why something went wrong. To retrieve this data, we use the following methods:
throw
new Exception("Message")).finally block is always executed (regardless of whether an error occurred or not), which is ideal
for tasks like closing open files or database connections.Exceptions are not intended for ordinary syntax errors (like a forgotten semicolon). We use them to handle external, unpredictable situations that the programmer has no direct control over—for example, when a remote API server fails to return data, when a user uploads the wrong file type, or when a database connection drops. By catching the error, you can display a friendly notification to the user instead of a raw red system error page.